Blairg23 Blairg23 - 1 year ago 48
Python Question

How do I run Python script from a subdirectory?

I want to be able to write a line of code like this and have it run smoothly:

python /path/to/ -arg1 -arg2 -etc

I figured out an easy way to discover all modules and add them to the current Python path, but it still doesn't seem to recognize the .py file, even though it's supposedly in the
. I know the
addition is working because I can perform this in the interpreter just fine:

>>>import ModuleManager # My Python script to discover modules in lower directories
>>>import testModule # Module I want to run from lower directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named testModule

>>>ModuleManager.discoverModules() # Now, I find the modules and add them to path
Discovering Modules...Complete!
Discovered 6 Modules.
>>>import testModule # No error now.

What I would like to do at this point is be able to go into my terminal and say:

python testModule -arg1 -arg2 -etc

and have it perform how I would expect.

To be clear, I want to write a line of code in
(from my application root folder) that allows me to access a file named
which is found in
in a way such that I can use arguments as in
python -arg1 -arg2 -etc
. Any suggestions?

Answer Source

How to call from Python another Python script

You want to call a Python script, which works well only if run from particular directory as it has some imports which work well only from given location.

Assuming there is a subdirectory named "script_dir" and there is the "" file:

import subprocess["python", ""], cwd="script_dir")

If your script accepts command line arguments "arg1", "arg2", "-etc"

import subprocess["python", "", "arg1", "arg2", "-etc"], cwd="script_dir")