2017-04-21 150 views
0

以下是我試圖運行如何運行蟒蛇Windows命令行命令時,命令有雙引號

device_editor_path = os.path.join(syntax_checker_path,'DeviceEditor.jar') 
output_path = os.path.join(reviewdocs_path,'syntaxchecker_orig_output.txt') 
output_path = '"%s"' % output_path # Need to do this because in case there is a space in output_path 
# run syntax checker 
cmd = 'java -jar' + ' ' + device_editor_path + ' ' + content_data_path + ' ' + event_source_name 
if version == 'v2': 
    cmd = cmd + ' ' + '-v2' 
final_cmd = cmd + ' ' + '>' + ' ' + output_path 
# final_cmd_test = r'java -jar C:\TOOLS_UI\syntaxchecker\DeviceEditor.jar C:\Users\patela28\Perforce\content-dev\dev\envision\content\content-data\ symantecav -v2 > "C:\Users\patela28\Desktop\jira\ESU#105\Sprint_27\SMC-112\ReviewDocs&Checklist\syntaxchecker_orig_output.txt"' 
print(final_cmd) 
status = os.system(final_cmd) 

打印的輸出代碼(final_cmd)是

Java的罐子C:\ TOOLS_UI \ syntaxchecker \ DeviceEditor.jar C:\ Users \ patela28 \ Perforce \ content-dev \ dev \ envision \ content \ content-data \ symantecav -v2>「C:\ Users \ patela28 \ Desktop \ jira \ ESU #105 \ Sprint_27 \ SMC-112 \ ReviewDocs & Checklist \ syntaxchecker_orig_output.txt「

Thi s命令確實運行,但命令行上顯示的整個輸出並沒有被重定向到syntaxchecker_orig_output.txt。

當我複製粘貼命令行上面的相同的命令它完美的作品,我得到一個syntaxchecker_orig_output.txt文件的位置。

無法弄清楚爲什麼會發生這種情況。

回答

0

您必須啓動命令處理器。 Java不會爲你分析命令行。下面應該工作:

device_editor_path = os.path.join(syntax_checker_path,'DeviceEditor.jar') 
output_path = os.path.join(reviewdocs_path,'syntaxchecker_orig_output.txt') 
output_path = '"%s"' % output_path # Need to do this because in case there is a space in output_path 
# run syntax checker 
cmd = 'cmd.exe /c java -jar' + ' ' + device_editor_path + ' ' + content_data_path + ' ' + event_source_name 
if version == 'v2': 
    cmd = cmd + ' ' + '-v2' 
final_cmd = cmd + ' ' + '>' + ' ' + output_path 
# final_cmd_test = r'java -jar C:\TOOLS_UI\syntaxchecker\DeviceEditor.jar C:\Users\patela28\Perforce\content-dev\dev\envision\content\content-data\ symantecav -v2 > "C:\Users\patela28\Desktop\jira\ESU#105\Sprint_27\SMC-112\ReviewDocs&Checklist\syntaxchecker_orig_output.txt"' 
print(final_cmd) 
status = os.system(final_cmd) 
0

不知道的原因,但改變

final_cmd = CMD + '' + '>' + '' + output_path

final_cmd = cmd +''+'>'+ output_path

爲我工作。

+0

這似乎不可靠,可能是cmd.exe中的某種解析錯誤。嘗試將原始命令行用雙引號括起來,例如'os.system('「%s」'%final_cmd)'。在這種情況下,cmd應該剝離第一個和最後一個引號,否則就像命令行是批處理文件中的一行那樣解析命令行。 – eryksun

+0

最終你會更好地使用'subprocess.Popen'解決這個問題。只需打開輸出文件並使用標準輸出重定向到文件來運行base命令,例如'p = subprocess.Popen(cmd,stdout = output.fileno())'。 – eryksun