Python 不会运行整个 shell 脚本?

标签 python linux bash shell

从以下代码开始,我的目标是为我的 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/

相关文章:

git - 是否可以将 git 提交消息保存到预提交 Hook 中的文件中?

python - 使用 Shapely 绘制椭圆

linux - 使用 Awk 和 ifconfig 定义 UNIX 别名和/或函数

linux - 从 bash 文件运行查找命令

python - 创建表准备好的语句错误1064

sql - 在 MySQL 中创建/写入权限

bash - xargs -l 的替代品

python - Python 中函数的彩色网格图

python - PySpark 逐行函数组合

python - 从音频脉冲中获取二进制数据