问题产生的原因:pycharm自动将代码的主函数路径加入到运行中去,但是linux不会。
解决问题的本质:为项目中文件找到更目录并添加到sys路径中。
项目实例
原始的项目文件中, 所有的文件都没有__init__.py文件。
1. 实验1: file0调用file1,file2实现
file0.py
from src.dir1 import file1 from src.dir2 import file2 def fun0(): return "fun0 is the root path, test_dir_level" if __name__ == '__main__': print(file1.fun1()) print(file2.fun2())
file1.py
def fun1(): return "file1 is in the dir1"
file2.py
def fun1(): return "file1 is in the dir1"
进入file0所在目录, 运行文件得到:
结果分析: 此时,运行正常,file0文件能够调用file1和file2中的方法。
2. 实验2:file1调用file2中方法(file2调用file1也一样)
file1.py中内容为:
from src.dir2 import file2 print(file2.fun2())
file2.py 内容与实验1中给出的相同。
此时,linux进入file1所在的文件运行file.py,结果如下:
但是在pycharm中可以正常运行,结果为:
3. 解决办法
解决实验2中的问题(file1调用file2失败的问题)
方式1:在file1的文件中,添加下面的内容,将更目录添加到sys.path中,此时,file1.py内容如下:
import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] add_path = os.path.split(rootPath)[0] sys.path.append(os.path.split(rootPath)[0]) from src.dir2 import file2 print(file2.fun2())
进入file1所在的路径,运行python file1.py,也可以正常调用到file2.
方式2: 在file1.py所处的文件夹下添加__init__.py文件,内容如下:
import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(os.path.split(rootPath)[0])
file1.py中添加
from __init__ import *
file1.py 代码为:
from __init__ import * from src.dir2 import file2 print(file2.fun2())
此时,运行 python file.py
注: 一定要在file1.py中添加from __init__ import *,否则依然会报错No module named src