Subprocess.Popen()=>无输出

7 python subprocess stdout popen

我试图从Python中运行一个Perl脚本,但是在stdout()中没有输出,而当我从shell运行它时,我的脚本完全正常.

首先,这是我如何从shell执行它(假设我在正确的目录中):

./vmlinkedclone.pl --server 192.168.20.2 --username root --password root 
--vmbase_id 2 --vm_destination_id 41 --vmname_destination "clone-41-snapname" --snapname Snapname

#=> True, []
#=> or False, and a description of the error here 
#=> or an argument error
Run Code Online (Sandbox Code Playgroud)

以下是我尝试从Python调用它的方法:

cmd = ['/home/user/workspace/vmlinkedclone.pl', '--server', '192.168.20.2', '--username', 'root', '--password', 'root' ,'--vmbase_id', '2', '--vm_destination_id', '41', '--vmname_destination', 'clone-41-snapname', '--snapname', 'Snapname']
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = pipe.stdout.read()

print "Result : ",result
#=> Result :
Run Code Online (Sandbox Code Playgroud)

当我从Shell运行脚本时,为什么我得到所需的输出,而从Python中什么也得不到?

Pul*_*mon 8

你能尝试一下:

pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

编辑

我确实发现了一些与编码相关的问题,我以下面的方式解决了它:

import subprocess
cmd = ['/home/user/workspace/vmlinkedclone.pl', '--server', '192.168.20.2', '--username', 'root', '--password', 'root' ,'--vmbase_id', '2', '--vm_destination_id', '41', '--vmname_destination', 'clone-41-snapname', '--snapname', 'Snapname']
pipe = subprocess.Popen(cmd, shell = True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pipe.communicate()
result = out.decode()
print "Result : ",result 
Run Code Online (Sandbox Code Playgroud)

  • 您也可以尝试打印错误以查看是否遇到任何错误:print"Error",错误 (3认同)