【问题标题】:Python program throwing error when called through subprocessPython程序通过子进程调用时抛出错误
【发布时间】:2021-05-12 01:33:50
【问题描述】:

我有一个简单的python文件myfile.py

#!/usr/bin/python

def on_message(ws, message):
    if message == 'pong':
       pong = True
       receiver_exists = True

def on_error(ws, error):
    print("### error ###", error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    print('### connected ###')
   

if __name__ == "__main__":

import websocket
import _thread as thread
import time
import re
from camera import VideoCamera
from deviceSpecificVals import machineSerial, token
    while True:
        try:
            uri = f"ws://myurl/stream/{machineSerial}/?{token}"
            ws = websocket.WebSocketApp(uri,
                              on_open = on_open,
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)

            ws.run_forever()
        except:
            pass

当我通过简单地从终端执行它来运行它时,它会按预期工作。 当我尝试从另一个 python 程序运行它时,使用: os.system('myfile.py') 或者 subprocess.Popen(['myfile.py'], stdin=subprocess.PIPE)

两者都会抛出错误ImportError: No module named websocket

为什么它在终端上可以正常工作,但不使用 os.system 或子进程

【问题讨论】:

  • 你是在终端运行它 - myfile.py 还是 python myfile.py?您是否安装了其他 Python?你在运行/usr/bin/python myfile.py的时候有这个问题吗?也许它与其他 Python 一起运行。也许你应该在代码中使用不同的 shebang - 即 #!/usr/bin/python3 ?您可以添加显示有关使用的 Python、当前工作字典等信息的代码。
  • 将此更改为答案,我将其标记为答案。 shebang (python3) 做到了,不错

标签: python


【解决方案1】:

有时计算机可能安装了两个(或更多)Python(尤其是 Linux/Unix),它可能需要正确的 shebang 才能以预期的版本运行它

#!/usr/bin/python3 

#!/usr/bin/python3.8 

也可以在虚拟环境中安装版本运行

#!/usr/bin/env  python3 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 2017-10-22
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多