【问题标题】:call python script function from other directory从其他目录调用 python 脚本函数
【发布时间】:2020-03-13 12:10:39
【问题描述】:

试图从其他目录调用 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脚本所在的目录相同,则在下面工作 没有任何问题:-

python -c '从 foo 导入 *; hii()'

但如果 python 脚本位于子目录中,则以下尝试无效:-

python -c '从 eg/foo 导入 *; hii()'

python -c '从 eg.foo 导入 *; hii()'

python -c '从 eg.foo.py 导入 *; hii()'

机器上的python版本是2.7.16

【问题讨论】:

  • 为什么 python 从相对路径导入简单的东西变得如此复杂?在不同的门户和复杂的解决方案链上有许多Q。在其他 C++、Java 等中,这是直截了当的方法。

标签: python-2.7 function relative-path


【解决方案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 目录中。你得到它工作了吗?

【讨论】:

    【解决方案2】:

    这对我有用->

    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")
    

    【讨论】:

    • Traceback(最近一次调用最后一次):文件“”,第 1 行,在 中 ImportError: No module named eg
    • eg 是另一个 foo 代码所在的目录。你创造的吗?
    • 在 github 上创建了一个示例,github.com/moglideveloper/pyCall
    • 是的..正确的代码..它对我有用..你还面临挑战吗?
    • ~/playground/octagon/bucket/pythonImport $ sh pyCall.sh Traceback(最近一次调用最后一次):文件“”,第 1 行,在 中 ImportError:没有名为例如的模块
    【解决方案3】:

    你试过python -c 'from ./eg/foo import *; hii()'吗?也许你需要的只是一开始的./

    【讨论】:

    • 这行不通,因为它不会被解读为package,请看我的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2019-06-02
    相关资源
    最近更新 更多