[英]How to do this Python subprocess call without using shell=True?
For example, in /tmp I have files ending in .txt, .doc, and .jpg that I'd like to delete in one step using shred and subprocess. 例如,在/ tmp中,我想以.txt,.doc和.jpg结尾的文件可以通过粉碎和子处理一步一步地删除。
The following does the job: 以下是工作:
subprocess.call('bash -c "shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}"', shell=True)
How would I do this command without using shell=True. 我如何不使用shell = True来执行此命令。 I've tried the following:
我尝试了以下方法:
subprocess.call(['bash', '-c', '"shred -n 10 -uz /tmp/{*.txt,*.pdf,*.doc}"'])
subprocess.call(['bash', '-c', 'shred', '-n 10', '-uz', '/tmp/{*.txt,*.pdf,*.doc}'])
Any suggestions? 有什么建议么?
I believe that other guy is spot on (haven't tried it myself though). 我相信有其他人在现场(虽然我自己没有尝试过)。 However if you ever find yourself having similar issues again shlex.split(s) might be helpful.
但是,如果再次遇到类似问题,则shlex.split(s)可能会有所帮助。 It takes the string 's' and splits it "using shell-like syntax".
它采用字符串“ s”,并“使用类似于shell的语法”将其拆分。
In [3]: shlex.split(s)
Out[3]: ['bash', '-c', 'shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}']
subprocess.call(['bash', '-c', 'shred -n 10 -uz /tmp/{*.txt,*.pdf,*.doc}'])
You can tell how a command is expanded and split up with: 您可以通过以下命令知道如何扩展和拆分命令:
$ printf "Argument: %s\n" bash -c "shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}"
Argument: bash
Argument: -c
Argument: shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}
In the more general case (but overkill here), if you're ever in doubt of what's executed by something with which parameters, you can use strace: 在更一般的情况下(这里是过度杀伤力),如果您不确定带有参数的对象执行的操作,可以使用strace:
$ cat script
import subprocess
subprocess.call('bash -c "shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}"', shell=True)
$ strace -s 1000 -fe execve python script
...
execve("/bin/bash", ["bash", "-c", "shred -n 5 -uz /tmp/{*.txt,*.pdf,*.doc}"], [/* 49 vars */]) = 0
...
$
If the command is coming from a trusted source eg, it is hardcoded then there is nothing wrong in using shell=True
: 如果命令来自可信来源,例如,它是经过硬编码的,那么使用
shell=True
并没有错:
#!/usr/bin/env python
from subprocess import check_call
check_call("shred -n 10 -uz /tmp/{*.txt,*.pdf,*.doc}",
shell=True, executable='/bin/bash')
/bin/bash
is used to support {}
inside the command. /bin/bash
用于在命令中支持{}
。
This command doesn't run /bin/sh
该命令不运行
/bin/sh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.