How do I run Python script from a subdirectory?

directory, import, module, python, terminal

Solution

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 "local_script_name.py" file:

import subprocess
subprocess.call(["python", "local_script_name.py"], cwd="script_dir")

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

import subprocess
subprocess.call(["python", "local_script_name.py", "arg1", "arg2", "-etc"], cwd="script_dir")

Problem

I want to be able to write a line of code like this and have it run smoothly: ``` python /path/to/python_file.py -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 `sys.path`. I know the `sys.path` 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 `ModuleManager.py` (from my application root folder) that allows me to access a file named `testModule.py` which is found in `/root/path/to/testModule.py` in a way such that I can use arguments as in `python testModule.py -arg1 -arg2 -etc`. Any suggestions?

Original source