Reputation: 175
Starting with the following code , my objective was to create a restart command for my python bot.
result = {
#cmds here
prfx and 'restart':lambda _: call('./restart.sh', shell=True),
}[cmd](_)
room.message(result)
I have a lot of commands in this dictionary so I summarized the format.
The command calls the shell script (restart.sh) , and is supposed to kill the bot process (bot.py) , and then reference to another shell script that then starts the bot process again.
[restart.sh]
pgrep -f bot.py # pid
pkill -9 -f bot.py # kills the matching pid
sh ./start.sh #run start.sh
exit 0
[start.sh]
python bot.py
When running the restart command , the bot process is ended and does not continue the rest of the script.
[example : Bash]
Connecting to MySQL database...
connection established.
Connection closed.
ONLINE
[chatroom] Bot: ONLINE!: [ip]
[chatroom] user: >restart: [ip]
168747
169448
It will just show the two processes and terminate.
Upvotes: 0
Views: 76
Reputation: 295363
To restart yourself (that is to say, the current process), don't use call()
(which I'm assuming is subprocess.call()
) at all.
Instead, if this code is being run from bot.py
itself (and that script is executable with a valid shebang):
os.execl(os.path.abspath(__file__), '_')
The _
is a placeholder passed as argv[0]
. You could put other command-line arguments after it, if you wished.
This replaces the running instance of bot.py
with a new one inheriting the exact same PID.
Upvotes: 1