使用子进程执行命令的区别
Difference in executing command with subprocess
我有这段代码执行得很好:
import subprocess
exe_cmd = subprocess.Popen(["ls", "-al"], stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output
我还有另一篇文章,我将命令分配给一个变量,然后将其作为参数传递。但在这种情况下它失败了。为什么?
import subprocess
#Here I assign the command to a variable.
cmd = "ls -al"
exe_cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output
你的 cmd 变量应该是
cmd = ["ls","-al" ]
On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.
所以你需要设置shell=True
On Unix with shell=True
, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.
(强调我的)
Popen
的第一个参数是一个参数列表,在你的第一个例子中你传递了它
["ls", "-al"]
在你的第二个例子中你传递给它一个字符串 "ls -al".
您可以将分配 ["ls", "-al"]
的代码更改为 cmd
。
你也可以使用shlex.split
来解析字符串并获取列表传递给Popen
如果要使用字符串作为 Popen 的第一个参数,则需要在调用中设置 shell=True
。否则它会尝试查找具有完整字符串和 运行 的可执行文件,在这种情况下当然不存在。
我有这段代码执行得很好:
import subprocess
exe_cmd = subprocess.Popen(["ls", "-al"], stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output
我还有另一篇文章,我将命令分配给一个变量,然后将其作为参数传递。但在这种情况下它失败了。为什么?
import subprocess
#Here I assign the command to a variable.
cmd = "ls -al"
exe_cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output
你的 cmd 变量应该是
cmd = ["ls","-al" ]
On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.
所以你需要设置shell=True
On Unix with
shell=True
, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.
(强调我的)
Popen
的第一个参数是一个参数列表,在你的第一个例子中你传递了它
["ls", "-al"]
在你的第二个例子中你传递给它一个字符串 "ls -al".
您可以将分配 ["ls", "-al"]
的代码更改为 cmd
。
你也可以使用shlex.split
来解析字符串并获取列表传递给Popen
如果要使用字符串作为 Popen 的第一个参数,则需要在调用中设置 shell=True
。否则它会尝试查找具有完整字符串和 运行 的可执行文件,在这种情况下当然不存在。