Run python script in subfolder

Hi,

Please check the following picture which explains my questions.
In Linux, in Top Folder, if I run python Scripts/SC1.py, the error is:ModuleNotFoundError: No module named 'package1'

if I create a soft link in Top Folder using command: ln -s Scripts/SC1.py SC1.py, and then run command: python SC1.py, I still experience the same error.

I don’t want to mv SC1.py to Top Folder, how could I run it in Linux?

Why not? It is the standard way of doing things.

When you run a script, the directory of the script is added to the PYTHONPATH, not the current directory. So anything below Top Folder, but not below Scripts, becomes unreachable for the loader.

You can of course add the folder to the path, but I would put a script (could be just a small bootstrap) into the Top Folder to start your program.

There are several options, listing from most to least recommended:

  1. Make a caller script under the top folder, that wraps the scripts under Scripts. You can import members into the caller script
  2. Run as a module: python -m Scripts.SC1, although it works, it doesn’t look good because Scripts isn’t a module.
  3. Add the top-level path to the sys.path in each scripts under Scripts folder. It is highly not recommended but provided as an option.

@Mholscher
@frostming
Thank you for your help!

I created a soft link in Linux ln -s Scripts/SC1.py SC1.py, and open Top Folder in VSCode in Windows 10.
I could run the soft link SC.py in VSCode.
My question is:
how could vscode run soft link SC1.py in Top Folder but the soft link couldn’t be run in Linux terminal?

I am really not in a position to tell. There are three participants here: the OS, Python and VS Code. I wouldn’t even know where the culprit would be.

Wild guess
Probably in the terminal Python finds out where the file executing ( Scripts/SC1.py) is located and adds that folder to the path :frowning_with_open_mouth: while VS Code adds the current directory to the path.

Option 1 and 2 that @frostming suggested seem both fine to me. Go with one of those.

VS Code has its own Workspace environment. I suspect that the Workspace is providing a path in addition to your OS’s path.