Search code examples
python-2.7functionrelative-path

call python script function from other directory


Trying to call function of a python script from some other directory. Below is the simplified example:-

~/playground/octagon/bucket/pythonImport/eg $

pwd
/Users/mogli/playground/octagon/bucket/pythonImport/eg

~/playground/octagon/bucket/pythonImport/eg $

ls
foo.py

~/playground/octagon/bucket/pythonImport/eg $

cat foo.py
import sys

def hello():
    print('Hello :)')

def hii():
    print('Hii :)')

~/playground/octagon/bucket/pythonImport/eg $

python -c 'from foo import *; hii()'
Hii :)

~/playground/octagon/bucket/pythonImport/eg $

cd ..

~/playground/octagon/bucket/pythonImport $

ls
eg

~/playground/octagon/bucket/pythonImport $

python -c 'from eg/foo import *; hii()'
  File "<string>", line 1
    from eg/foo import *; hii()
           ^
SyntaxError: invalid syntax

~/playground/octagon/bucket/pythonImport $

python -c 'from eg.foo import *; hii()'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named eg.foo

~/playground/octagon/bucket/pythonImport $

python -c 'from eg.foo.py import *; hii()'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named eg.foo.py

If execution directory is the same directory, where the python script is there, then below wroks without any issue :-

python -c 'from foo import *; hii()'

But if python script is in child directory, then below attempts didn't worked :-

python -c 'from eg/foo import *; hii()'

python -c 'from eg.foo import *; hii()'

python -c 'from eg.foo.py import *; hii()'

python version on machine is 2.7.16


Solution

  • its working... pyCall.sh

    #!/bin/bash
    python -c "import sys;sys.path.append('./eg');import foo as foo1;foo1.hii()"
    

    Run

    sudo chmod +x ./pyCall.sh
    ./pyCall.sh

    Make sure you have your foo file inside eg directory in this location.Did you got it working?