python - 使用 os.system() 问题在 Ubuntu 上终止进程

标签 python linux os.system

我尝试从 python shell 向 Ubuntu OS 发送命令来定义特定端口上存在的进程并终止它:

port = 8000
os.system("netstat -lpn | grep %s" % port)

输出:

tcp 0 0 127.0.0.1.8000 0.0.0.0:* LISTEN 22000/python

然后:

os.system("kill -SIGTERM 22000")

但得到了跟踪

sh: 1: kill: 非法选项 -S

由于某些原因,命令无法通过完整信号 -SIGTERM 传输到操作系统,而只能通过 -S 传输。我可以直接从 Terminal 终止这个进程,看来这是 Pythonos 问题...我如何运行 kill 命令使用 Python? 感谢任何帮助

最佳答案

os.system 使用 sh 来执行命令,而不是您在终端中获得的 bashsh 中内置的 kill 要求提供信号名称时不带 SIG 前缀。将 os.system 命令行更改为 kill -TERM 22000

[编辑] 正如@DJanssens 建议的那样,使用 os.kill 比调用 shell 来处理这种简单的事情更好。

关于python - 使用 os.system() 问题在 Ubuntu 上终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585099/

相关文章:

c++ - Python 和 C++ 代码比较

python - python脚本中的os.system错误

c - linux 函数 inet_ntoa 会导致 dns 查询吗?

python - os.system 不工作,但在命令提示符下输入同样的东西可以工作

python - 需要在 python 中通过 espeak 和 aplay 命令使用 os.system 中的变量

python - DeleteView 标记为不活动而不是删除?

Java 使用 JNI 导入使用第 3 方功能的 C 中的共享库 (Python.h)

python - 保存引用字段 mongoengine

c - 编译器 gcc 错误 : undefined reference to `main'

linux - 使用通配符搜索并在同一行替换