Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script within python package

Tags:

python

package

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 we 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.

like image 262
ojy Avatar asked Nov 07 '14 23:11

ojy


1 Answers

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
like image 104
Fred S Avatar answered Oct 05 '22 02:10

Fred S