1

I have a simple python file 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

When I run this by simply executing it from the terminal it works as expected. When I try to run this from another python program using: os.system('myfile.py') or subprocess.Popen(['myfile.py'], stdin=subprocess.PIPE)

Both will throw the error ImportError: No module named websocket

Why does it work fine from terminal but not using os.system or subprocess

2
  • 2
    do you run it in terminal - myfile.py or python myfile.py? Do you have other Pythons installed? Do you have this problem when you run /usr/bin/python myfile.py? Maybe it runs with other Python. maybe you should use different shebang in code - ie #!/usr/bin/python3 ? You could add code which display information about used Python, current working dictionary, etc. Commented May 12, 2021 at 2:15
  • Change this to answer and I will mark it as such. The shebang (python3) did it, good catch Commented May 12, 2021 at 9:42

1 Answer 1

2

Sometimes computers may have two (or more) Pythons installed (especially Linux/Unix) and it may need correct shebang to run it with expected version

#!/usr/bin/python3 

or

#!/usr/bin/python3.8 

To run also with version installed in virtual environment

#!/usr/bin/env  python3 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.