我有一段执行良好的代码:
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
请您参考如下方法:
如果您想使用字符串作为 Popen 的第一个参数,您需要在调用中设置 shell=True。否则它会尝试找到具有完整字符串的可执行文件并运行它,在这种情况下当然不存在。
