python在pycharm中运行正常,无法在cmd或terminal中通过命令运行,找不到模块

假如我在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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值