简体   繁体   English

subprocess.Popen产生错误,而命令在命令行中运行顺畅(错误:查找:路径必须在表达式之前)

[英]subprocess.Popen produces error while, commands run smoothly in command line (ERROR: find: paths must precedeexpression)

I am trying to incorporate a few commands into a python script that I typically would use in a command line (Ubuntu 14.04) to deal with files. 我正在尝试将一些命令合并到python脚本中,通常在命令行(Ubuntu 14.04)中使用该命令来处理文件。

I tried following the example on the subprocess help page , but it hits me with the following error message: 我尝试按照子流程帮助页面上的示例进行操作,但由于出现以下错误消息而使我震惊:

find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

The reason, I am a little stumped is that it excutes properly, if I type it directly in the console. 原因是,如果我直接在控制台中键入它,它会正确执行。 I am suspecting there is something wrong how the arguments are parsed, but imo the printed out results for argv1 and argv2 to looked like expected (based on the example). 我怀疑如何解析参数有问题,但是imo argv1argv2的打印结果看起来像预期的那样(基于示例)。

import subprocess, shlex



cmd1 = "find . -name *.tgz | xargs -i pigz -dv {}"
cmd2 = "find . -name *.tar | xargs -i tar -xfv {} -C decompressed --wildcards '*B5.TIF' '*B6.TIF' '*B8.TIF' "

args1 = shlex.split(cmd1)
args2 = shlex.split(cmd2)

print args1
print args2 

subprocess.call(args1)
subprocess.call(args2)

I tried subprocess.call() and subprocess.Popen() with the same results. 我尝试了subprocess.call()subprocess.Popen()具有相同的结果。 Any suggestions are greatly appreciated. 任何建议,不胜感激。

subprocess.Popen(args1,shell=True) or subprocess.call(args1,shell=True) with shell=True works fine on Ubuntu 14.04 for me. subprocess.Popen(args1,shell=True)subprocess.call(args1,shell=True)shell=True在Ubuntu 14.04上对我来说很好用。

Warning Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. 警告执行包含来自不受信任源的未经处理的输入的Shell命令会使程序容易受到Shell注入的攻击,这是一个严重的安全漏洞,可能导致任意命令执行。 For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input : 出于这个原因,在命令字符串是由外部输入构造的情况下强烈建议不要使用shell = True:

I believe you're running into this error because of the pipes in your commands. 我相信您由于命令中的管道而遇到此错误。

You'll want to do something like this instead (this is just for cmd1): 您将改为执行以下操作(这仅适用于cmd1):

cmd1=`find . -name *.tgz | xargs -i pigz -dv {}`
# should instead be
p1 = subprocess.Popen(["find", ".", "-name", "*.tgz"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["xargs", "-i", "pigz", "-dv", "{}"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

For more details read the subprocess documentation . 有关更多详细信息,请阅读子流程文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM