pythonvisual-studio-codepatharcade

Running code in Visual Studio Code vs. command line (incompatible file extensions)


I have been developing an application using Visual Studio Code and running it via Visual Studio Code's built-in terminal. My application uses texture loading via the arcade library.

Example:

texture_a = arcade.load_texture("Version 1\Images\texture_a.png")

My application works fine/ loads and displays the textures when using Visual Studio Code, but when I try to run the Python file from the command line, I get a "Cannot locate resource" error. Why does the path work when running from Visual Studio Code terminal, but doesn't work from the normal terminal?

I am using Windows 11.


Solution

  • This is usually a problem with the so-called working directory. VS Code may run your script with a different working directory than the path you start the script from in the terminal. Try importing os at the start of your script and adding something like print(os.getcwd()), and compare what you see in both cases.

    In your case, you see C:\Users\myName and W:\Code Files\ApplicationName. What does that mean?

    Any program (across OSes even) has a working directory. All relative paths are relative to that working directory. For example, if you open('test.txt') it will be opened in that directory. Only if you specify an absolute path (like open('C:\Temp\test.txt')) does the working directory not matter.

    In your case, if you need to open Version 1\Images\texture_a.png, you have some options:

    1. Accept that this is relative to where the user of your script starts the script; this can be useful, for example if your script was designed to operate on some files in a directory of a user's choosing.

    2. Provide an absolute path, if you need that image to be in a specific location, regardless of where the script is, or where it was started. For example C:\Users\myName\Version 1\Images\texture_a.png instead of relying on that being the working directory.

    3. Change the working directory to where the script should be running, so you can keep using the same relative paths: os.chdir('C:\Users\myName') before opening any files, so that this will be the working directory (assuming you can be sure it exists).

    You can also find out where the script itself is (with something like pathlib.Path(__file__).parent) and use that as a prefix to your paths, or as the working directory for files you open.