【问题标题】:How to run complex python commands using subprocess using relative reference?如何使用相对引用使用子进程运行复杂的 python 命令?
【发布时间】:2017-05-24 16:10:05
【问题描述】:

我正在尝试使用 Python 执行此命令:

findSyntax = "find . -maxdepth 2 -name '.config' | cpio -updm ../test1/"
subprocess.Popen(findSyntax.split(' '))

但是这个命令是行不通的。当我执行此命令时,它将开始列出 .config 下的所有文件(不仅仅是 .config)。超出 maxdepth 2 的目录...这是一个很长的列表。

我在这里错过了什么!有人可以指出吗?谢谢。

注意:我也尝试过运行subProcess.run,结果相同。我能够使用 os.system() 命令让 find 部分正常工作。

编辑:我只是想澄清一下,此命令会将找到的具有完整目录结构的文件复制到新位置(如有必要,创建子目录)。我在 bash 终端上试过这个命令,它工作正常。但我无法让它与 Python 一起使用。

EDIT2:所以,整个命令适用于os.system(),但我不知道如何使其适用于subprocessos.system() 应该被弃用,所以我很想用subprocess 来找出解决方案。

【问题讨论】:

  • 你应该说出你期望发生的事情。
  • 你应该剖析一些东西。首先确保您的 find “找到”了您期望它找到的内容 - 当您从命令行手动运行它时!然后:你可能想使用 shlex 模块而不是仅仅拆分你的命令。
  • @GhostCat,我已经用一些细节编辑了这个问题。该命令在 shell 上运行良好。我不知道他的 shlex 模块,但我会谷歌它。
  • 检查您的路径。如果您可以通过 bash 运行命令,它应该通过 os.system() 运行完全相同

标签: python linux unix subprocess


【解决方案1】:

请看this good answerthis also helps

但本质上,您不能将上述子进程命令与管道一起使用。

让我们看一下获取当前目录中所有py文件的简单示例:(ls | grep py)
这个坏了:

import subprocess
subprocess.call(['ls', '|', 'grep', 'py'])

因为 subprocess 一次只执行一个进程,而通过管道,您实际上是在创建 2 个进程。

简单但受限的(平台)方式是使用os.system

import os
os.system('ls | grep py')

这实际上只是将一个 shell 命令传递给系统执行。

但是,您应该通过定义管道来处理子流程:

# Get all files and pass the stdout to a pipe
p1 = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
# then pass that pipe to another process as stdin and do part 2
output = subprocess.check_output(['grep', 'py'], stdin=p1.stdout)
print(output)

所以,复制粘贴您的示例:

import subprocess
p1 = subprocess.Popen("find . -maxdepth 2 -name '.config'".split(), stdout=subprocess.PIPE)
output = subprocess.check_output("cpio -updm ../test1/".split(), stdin=p1.stdout)

或者os:

os.system("find . -maxdepth 2 -name '.config' | cpio -updm ../test1/")

【讨论】:

  • 感谢您的回复。我试过你的例子,但它也没有工作。我尝试按照here 的说明查看标准输出数据进行调试,它只打印了b''。我不确定这里发生了什么。
  • 你试过用os.system("find . -maxdepth 2 -name '.config' | cpio -updm ../test1/")运行你的命令吗?
  • @rrlamichhane 哦,我怀疑您的路径可能不正确。不要查看当前(python 脚本)路径.,而是输入绝对路径。
  • 你总是可以启动一个 bash 命令并将“管道”部分作为一个整体!
  • @Roman,不知道为什么我从来没有想过用os.system() 尝试整个命令,但我只是尝试了一下,它确实有效。我知道 Python 想要弃用 os.system(),但这不应该意味着像 subprocess 这样的新替代品应该能够运行 os.system() 可以运行的命令吗?
猜你喜欢
  • 2021-04-03
  • 1970-01-01
  • 2018-08-13
  • 2013-11-29
  • 2020-07-25
  • 2021-12-07
  • 1970-01-01
  • 2020-12-28
  • 2020-05-20
相关资源
最近更新 更多