2012-10-12 25 views
2

錯誤消息:蟒蛇調用外部cmd並stdout重定向到文件

Failed to open output_file_path/**.txt 

代碼:

cmd = 'showTxt "%s" > "%s"' % (file_path, output_file_path) 
LoggerInstance.log('[cmd] '+cmd) 

#os.system(cmd) 
splited_cmd=shlex.split(cmd) 

p = subprocess.Popen(splited_cmd, stderr=subprocess.PIPE) 
#p.wait() 
output = p.stderr.read() 
print output 

LoggerInstance.log('[console std error]'+ output) 

如何標準輸出重定向到一個cmd文件?

+0

'output_file_path'的值是什麼? –

+1

'Popen(splited_cmd,stdout = open(output_file_path,「w」),stderr = subprocess.PIPE)' –

+1

據我所知,你不能在你調用的命令中使用管道,你必須創建兩個子進程,用另一個stdin作爲stdin。太複雜!您可以使用python將stout保存到文件中,也可以將命令放入shell腳本中並使用子進程調用該文件。 –

回答

2

您可以到Popen提供file-handler作爲stdout參數,即:

p = subprocess.Popen(splited_cmd, 
        stderr=subprocess.PIPE, 
        stdout=open(output_file_path, "w")) 

當然,準備捕獲異常,它可以拋出。