尝试从其他目录调用python脚本的功能。 下面是简化的示例:-
~/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
如果执行目录与python脚本位于同一目录,则在wroks下面 没有任何问题:-
python -c'from foo import *; hii()'
但是,如果python脚本位于子目录中,则以下尝试均无效:-
python -c'from eg / foo import *; hii()'
python -c'from eg.foo import *; hii()'
python -c'from eg.foo.py import *; hii()'
机器上的python版本是2.7.16
答案 0 :(得分:-1)
这对我有用->
python -c "from eg import foo as foo1;foo1.hi()"
Inside Eg Foo
python -c "import foo as foo;foo.hi()"
Inside First FOO
但是,如果在脚本内部使用此命令,则需要使用以下命令在路径变量中添加主路径。
import sys
sys.path.append("Your main path")
答案 1 :(得分:-1)
您尝试过python -c 'from ./eg/foo import *; hii()'
吗?也许您只需要在开始时使用./
。
答案 2 :(得分:-1)
正在工作... pyCall.sh
#!/bin/bash
python -c "import sys;sys.path.append('./eg');import foo as foo1;foo1.hii()"
运行
sudo chmod + x ./pyCall.sh
./pyCall.sh
确保您的foo文件位于此位置的eg目录中。您能正常使用吗?