Run script within python package

2020-04-12 08:35发布

问题:

How to run a script within the module when the module is not in my Python path?

Consider some imaginary package:

package/
     __init__.py
    main.py
    helper/  
        __init__.py
        script.py
    other/  
        __init__.py
        anotherscript.py

Say wee want to run script.py. When the package is in my Python path, this does the job:

python -m package.helper.script

But what if it's not the case? Is there a way to tell python the location of the module? Something like

python -m /path_to_my_package/package.helper.script

(clearly, the above doesn't work)

EDIT:

(1) I am looking for a solution that doesn't involve environmental variables.

(2) script.py contains relative import, so the full path to script.py does not solve the problem.

回答1:

You could do this. I assume this is from a cmd prompt or batch file?

SET PYTHONPATH=..\..\path\to\my\package;c:\other\path\thats\needed
python -m package.helper.script

You could also just pass the full path to your python file. But that assumes your script is not expecting a particular environment path to be pre-set for it.

python -m path_to_my_package/package/helper/script.py

EDIT - If your script.py uses relative imports (and you don't want to change that), then there is no way to do it except getting that root path into the environment. You can do this in your script if you want, instead of setting it in the cmd shell or batch file. But it needs to get done somewhere. Here's how you can set the environment path in your script:

import sys
sys.path.append(r'..\..\path\to\my\package')
import package.other.anotherscript


回答2:

Your script.py should look like:

#!/usr/bin/python

#here your python code

if __name__ == "__main__":
    #run you helper

Then make your script executable: chmod +x script.py.

Run ./path_to_my_package/package/helper/script.py from console.