假如我在pycharm里面写了一个这样的程序:
my2里面的hello函数:
def hello():
print("this is another hello!")
myCompany里面的hello函数:
def hello():
print("this is hello function")
主函数:
import myCompany.hello as mh
import my2.hello as my2h
if __name__ == '__main__':
mh.hello()
my2h.hello()
在pycharm下运行结果是这样的:
this is hello function
this is another hello!
但是在terminal或者cmd下用命令运行时这样的:
D:\projects\httpT1\main>python main.py
Traceback (most recent call last):
File "main.py", line 10, in <module>
import myCompany.hello as mh
ModuleNotFoundError: No module named 'myCompany'
这个时候我们只要将当前项目的路径添加到主程序执行文件就可以了
import sys
sys.path.append("D:/projects/httpT1/")
import myCompany.hello as mh
import my2.hello as my2h
if __name__ == '__main__':
mh.hello()
my2h.hello()
结果在pycharm下和terminal和cmd下都是正常的:
D:\projects\httpT1\main>python main.py
this is hello function
this is another hello!