1

I am trying to use subprocess.run(['python3.9', "scripts/example.py"], check=True).

example.py uses a module, that I have added to the PYTHONPATH. However, whenever I run the above line, the module is not found.

The confusing part for me is, that printing sys.path inside of example.py I do see the path to my module. But when I am running os.system("which python") or os.system("echo $PYTHONPATH") inside example.py, it returns/prints nothing.

3
  • 1
    Are you using a virtual environment? -- Typically, you would want to use the exact same Python interpreter for the sub-process call, so you would write: subprocess.run([sys.executable, 'scripts/example.py', check=True), unless of course you really do want python3.9 explicitly and nothing else (which would be surprising). -- And finally, you should check the doc for the env parameter of subprocess.run. Commented Nov 22, 2022 at 12:57
  • Thank you! using sys.executable and setting the env parameter to a copy of my environment variables where I manually added the pythonpath I needed solved the issue for me. Thank you so much! This bug took me my whole day to fix :D Commented Nov 22, 2022 at 14:57
  • 1
    Running Python as a subprocess of Python is often dubious. The simple and elegant solution is to import the code you want to run, and not run it in a subprocess at all. Commented Nov 22, 2022 at 15:42

1 Answer 1

2

Looks like you need to check the doc for the env parameter of subprocess.run and set it appropriately.

Side note: typically you would want to use the exact same Python interpreter for the sub-process call, so you would write: subprocess.run([sys.executable, 'scripts/example.py'], ...), unless of course you really do want 'python3.9' explicitly and nothing else (which would be surprising).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.