从以下代码开始,我的目标是为我的 python 机器人创建一个重启命令。
result = {
#cmds here
prfx and 'restart':lambda _: call('./restart.sh', shell=True),
}[cmd](_)
room.message(result)
我在这本字典里有很多命令,所以我总结了格式。
该命令调用 shell 脚本 (restart.sh) ,并应该终止 bot 进程 (bot.py) ,然后引用另一个 shell 脚本,然后再次启动 bot 进程。
[重启.sh]
pgrep -f bot.py # pid
pkill -9 -f bot.py # kills the matching pid
sh ./start.sh #run start.sh
exit 0
[开始.sh]
python bot.py
运行重启命令时,bot进程结束,不会继续脚本的其余部分。
[示例: bash ]
Connecting to MySQL database...
connection established.
Connection closed.
ONLINE
[chatroom] Bot: ONLINE!: [ip]
[chatroom] user: >restart: [ip]
168747
169448
它只会显示两个进程并终止。
最佳答案
要重启自己(也就是说,当前进程),不要使用call()
(我假设是subprocess.call()
)。
相反,如果此代码是从 bot.py
本身运行的(并且该脚本可以使用有效的 shebang 执行):
os.execl(os.path.abspath(__file__), '_')
_
是作为 argv[0]
传递的占位符。如果愿意,您可以在其后添加其他命令行参数。
这会用继承完全相同 PID 的新实例替换正在运行的 bot.py
实例。
关于Python 不会运行整个 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473815/