简体   繁体   中英

How to run a windows command line command from python when the command has double quotes

Following is the code I am trying to run

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)

The output of print(final_cmd) is

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"

This command does run but the entire output shown on the command line and is not getting redirected to syntaxchecker_orig_output.txt.

When I copy paste the same above command on the command line it works perfectly and I get a syntaxchecker_orig_output.txt file at the location.

Not able to figure out why this is happening.

You have to start the command processor. Java won't parse for you the command line. The following should work:

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)

Don't know the reason but changing

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

to

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

worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM