我正在尝试使用 Python 执行此命令:
findSyntax = "find . -maxdepth 2 -name '.config' | cpio -updm ../test1/"
subprocess.Popen(findSyntax.split(' '))
但是这个命令是行不通的。当我执行这个命令时,它会开始列出 .config 目录下的所有文件(不仅仅是 .config)。超出 maxdepth 2 的目录...这是一个很长的列表。
我在这里错过了什么!有人可以指出吗?谢谢。
注意:我试过运行 subProcess.run
也得到了相同的结果。我能够使用 os.system()
命令让查找部分正常工作。
编辑:我只是想澄清一下,此命令会将找到的具有完整目录结构的文件复制到新位置(必要时创建子目录)。我在 bash 终端上试过这个命令,它工作正常。但我无法让它与 Python 一起工作。
EDIT2: So, the whole command works with
os.system()
, but I couldn't figure out how to make it work withsubprocess
.os.system()
is supposed to be deprecated, so I would be very interested in figuring out the solution usingsubprocess
instead.
最佳答案
请看this good answer和 this also helps
但本质上,您不能将上述子流程命令与管道一起使用。
让我们通过获取当前目录中所有 py
文件的简单示例:(ls | grep py
)
这是坏的:
import subprocess
subprocess.call(['ls', '|', 'grep', 'py'])
因为子进程一次只执行一个进程,而通过管道你实际上创建了 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/")
关于python - 如何使用相对引用使用子进程运行复杂的python命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564274/