Restart python thread with os.execl method - Stack Overflow

admin2025-04-17  4

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.

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.

Share Improve this question edited Feb 2 at 10:32 ZCGCoder 5342 gold badges10 silver badges30 bronze badges asked Feb 1 at 12:35 GiammariaGiammaria 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

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
)
转载请注明原文地址:http://anycun.com/QandA/1744828297a88183.html