Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python module with absolute path

For this file layout:

devel/
    pkg/
        __init__.py
        moduleA.py
        moduleB.py
        test/
            __init__.py
            test_A.py
            test_B.py

If I am in the directory which contains the pkg (devel), I can run:

python -m pkg.test.test_A

But what if I want to run the same but with absobule path? I tried:

python -m /Users/me/docs/devel/pkg.test.test_A

Assuming I don't want to do the following and change the directory in my bash script:

cd /Users/me/docs/devel/
python -m pkg.test.test_A

Is there any direct way from python command?

like image 825
Diolor Avatar asked Apr 16 '14 17:04

Diolor


People also ask

How do you pass an absolute path in Python?

Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

How do I run a full path in Python?

You could use $0 which is the name of the currently executing program, as invoked, combined with dirname which provides the directory component of a file path, to determine the path (absolute or relative) that the shell script was invoked under. Then, you can apply it to the python invocation.

How do I set the path for a Python module?

To make sure Python can always find the module.py , you need to: Place module.py in the folder where the program will execute. Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.

How do I load a Python path?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


1 Answers

Add /Users/me/docs/devel to your module search path:

PYTHONPATH=/Users/me/docs/devel python -m pkg.test.test_A
like image 171
chepner Avatar answered Oct 13 '22 10:10

chepner