简体   繁体   English

在python子进程中使用exec查找命令会产生错误

[英]find command with exec in python subprocess gives error

I'm trying to execute the following command using subprocess module (python) 我正在尝试使用子进程模块(python)执行以下命令

/usr/bin/find <filepath> -maxdepth 1 -type f -iname "<pattern>" -exec basename {} \;

But, it gives the following error : 但是,它会出现以下错误:

/usr/bin/find: missing argument to `-exec'

I am guessing it's to do with escaping some characters. 我猜它与逃避一些角色有关。 But not getting how to get over this. 但没有得到如何克服这一点。

Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

An answer on another question helped: https://stackoverflow.com/a/15035344/971529 另一个问题的答案有所帮助: https//stackoverflow.com/a/15035344/971529

import subprocess

subprocess.Popen(('find', '/tmp/mount', '-type', 'f',
              '-name', '*.rpmsave', '-exec', 'rm', '-f', '{}', ';'))

The thing I couldn't figure out was that the semi-colon didn't need to be escaped, since normally the semi-colon is interpreted by bash, and needs to be escaped. 我无法弄清楚的是,分号不需要被转义,因为通常分号由bash解释,并且需要被转义。

In bash this equivelent is: 在bash中,这种平等是:

find /tmp/mount -type f -name "*.rpmsave" -exec rm -f {} \;

One more hint: Using the syntax r'bla' allows using backslashs without having to quote them: 还有一个提示:使用语法r'bla'允许使用反斜杠而不必引用它们:

r'... -exec basename {} \;'

Provides better readability. 提供更好的可读性。

remember escaping " is required and also escaping \\ used before ; is also required 记得逃避"是必需的,也是逃避\\之前使用过;也是必需的

your command might look something like: 您的命令可能类似于:

p1 = subprocess.Popen(["/usr/bin/find", "<filepath> -maxdepth 1 -type f -iname \"<pattern>\" -exec basename {} \\;"])
p1.communicate()

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

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