将“os.system”转换为“Python”中的“子进程”

Converting `os.system` to `subprocess` in Python

我想在 Python 中 grep 一个 Linux 屏幕 ID 来检查这个屏幕是否存在。我想将我的 os.system 命令转换为 subprocess 命令。

来自这里:

os.system('screen -ls | grep -i ' + INSTANCE_NAME + ' >/dev/null')

对此:

subprocess.check_call(['screen', '-ls', '|', 'grep', '-i', INSTANCE_NAME])

os.system 命令可以正常工作,但 subprocess 命令不行。 subprocess.runsubprocess.callsubprocess.check_call有什么区别?有人可以帮我吗?

我在 Linux Ubuntu Server 20.04 LTS

上使用 Python 3.10

管道 | 是一个 shell 命令,它将一个进程的输出连接到另一个进程的输入。如果你想在 subprocess 中使用它,你必须告诉 subprocess 函数你想要 运行 shell 中的命令,像这样:

subprocess.check_call('screen -ls | grep -i ' + INSTANCE_NAME, shell=True)

如果您使用它,您应该考虑 shell 调用的 security considerations。如果你想在没有 shell 的情况下实现同样的事情,你必须使用两个子进程。这是一个例子:

p1 = subprocess.Popen(["screen", "-ls"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(
    ["grep", "-i", INSTANCE_NAME], stdin=p1.stdout, stdout=subprocess.PIPE
)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0].decode()

(见https://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline

And what are the differences between subprocess.run, subprocess.call and subprocess.check_call? Can someone help me out?

documentation 提供了有关这些函数之间差异的大量信息。 TL;DR 是:

  1. callcheck_call 是旧的高级 API 的一部分,而 run 是调用子流程的新推荐方法。
  2. call:运行是一个命令,return是它的return代码
  3. check_call:类似调用,但如果 return 代码不是 0
  4. 则引发异常
  5. run:好吧,你可以访问 return 代码,输出,你可以为非零代码提高等等。文档包含所有信息。