pythonpython-3.xos.execl

Restart python thread with os.execl method


I am running a Python 3 script with flag -u to send output to a file like a log The exact command i use is

/usr/bin/python3 -u /home/pi/MyScript.py >> /home/pi/myScript.log

This works like a charm.

Now for some reason I need to restart the MyScript.py to re-initialize some functions inside, so I have found that os.execl function could be the right solution.

My problem is understand how to pass the -u and >> options to command, maybe it will be very easy but I'm spending a lot of time without result...

I have tried a lot of ways, one for example is this:

os.execv('/usr/bin/python3', ['/usr/bin/python3'] + ['-u'] + ['./PythonMqttMaster.py'] + [' >> '] +['PythonMqttMaster.log'])

but the output go to terminal instead of another file, without error.

Maybe I'm using a totally wrong approach, let me know if so.


Solution

  • You can use the os.execl function to start a shell and pass your entire command import os

    # Restart the script with shell redirection
    os.execl(
        '/bin/sh',  # Path to the shell executable
        'sh',       # First argument (name of the shell)
        '-c',       # Flag to pass the command as a string
        '/usr/bin/python3 -u /home/pi/MyScript.py >> /home/pi/myScript.log'  # Command with redirection
    )