python - pkill -f 在 shell 脚本中不起作用
问题描述
我有一个名为的 shell 脚本kill.sh
,可以帮助我重新启动我编写的 python 脚本。我通常pkill -f main.py
用来杀死我永远运行的 python 脚本。但是,当我将它写入 shell 脚本时,它不起作用。
我的剧本
pkill -f main.py
ps aux | grep main.py # Still shows the process running.
虽然只是pkill -f main.py
在 bash 命令行中执行,但可以按预期工作。为什么是这样?
解决方案
这不是一个令人满意的答案,因为我无法找出为什么pkill -f
在脚本中不起作用的根本原因。我最终使用systemd
服务文件来管理我的 python 进程。这是一个示例,仅供参考。
[Unit]
Description=Service Name
[Service]
Environment=PYTHONUNBUFFERED=1
ExecStart=/path/to/python /path/to/python/script.py
Restart=on-failure
RestartSec=5s
WorkingDirectory=/python/project/dir/
命名文件main.service
并将其放入/lib/systemd/system/
- 运行服务
systemctl start main.service
- 停止服务
systemctl stop main.service
- 重启服务
systemctl restart main.service
- 显示状态和输出
systemctl status main.service -l
现在我不必担心多个进程正在运行。如果程序死了,它甚至会重新启动。
推荐阅读
- python - 无法使用 conda 安装 Pygame
- javascript - 如何在 svelte 中的 for 循环迭代之间更新 DOM?
- ios - 在 Swift UITextFieldDelegate 中如何在编辑文本时触发动作?
- python - 如何在 kubeflow 管道中定义管道级卷以跨组件共享?
- java - 我可以在 Java 的循环中为一系列值创建变量名吗?
- awk - 识别 awk 字段分隔符中的反斜杠
- python - 如何使用 tf.keras.preprocessing.image.smart_resize(image, IMAGE_SIZE)?
- d3.js - d3.scaleBand 中的填充
- oracle-apex - 是否所有使用 20.1 之前的版本开发的应用程序都易受攻击?
- junit5 - 如何按特定顺序运行 Jupiter 测试类?