首页 > 解决方案 > 运行 python 脚本时出现问题,该脚本依赖于来自终端的其他文件?

问题描述

我需要您的帮助来解决以下问题-

我有一个结构化的 python 项目,其中有 3 个目录-A、B、C 在这些目录中有 python 文件-f1.py、f2.py、f3.py

文件夹 A 的 f1.py 文件正在使用写在文件夹 B 的 f2.py 中的函数(myfunc)。

我在 f1.py 文件中导入了 B 的 f2.py,当我运行它时,它可以在 Pycharm IDE 中运行。

现在,如果我想从终端(linux 终端)运行 f1.py 文件,那么它会说 - 没有名为 B.myfunc 的模块

如何从终端/cmd 运行 f1.py 而没有任何问题?

标签: linuxpython-3.6

解决方案


# file structure
./A/f1.py
./B/f2.py
./C/f3.py


$ cat A/f1.py B/f2.py C/f3.py
def myfunc():
    print(__name__)
def myfunc():
    print(__name__)
def myfunc():
    print(__name__)


$ python
Python 3.6.5 (default, Apr 25 2018, 14:26:36)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import A.f1
>>> import B.f2
>>> import C.f3
>>>
>>> A.f1.myfunc()
A.f1
>>> B.f2.myfunc()
B.f2
>>> C.f3.myfunc()
C.f3
>>>


# or from file:
$ cat test.py
import A.f1
import B.f2
import C.f3

A.f1.myfunc()
B.f2.myfunc()
C.f3.myfunc()

$ python test.py
A.f1
B.f2
C.f3

推荐阅读