【问题标题】:How to run a windows command line command from python when the command has double quotes当命令有双引号时如何从python运行windows命令行命令
【发布时间】:2017-04-21 05:50:40
【问题描述】:

以下是我要运行的代码

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)

print(final_cmd) 的输出是

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"

此命令确实运行,但整个输出显示在命令行上,并且没有被重定向到 syntaxchecker_orig_output.txt。

当我在命令行上复制粘贴相同的上述命令时,它可以完美运行,并且我在该位置获得了一个 syntaxchecker_orig_output.txt 文件。

无法弄清楚为什么会发生这种情况。

【问题讨论】:

    标签: python windows os.system


    【解决方案1】:

    您必须启动命令处理器。 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)
    

    【讨论】:

      【解决方案2】:

      不知道原因但正在改变

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

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

      为我工作。

      【讨论】:

      • 这似乎不太可靠,可能是 cmd.exe 中的某种解析错误。尝试将原始命令行用双引号括起来,例如os.system('"%s"' % final_cmd)。在这种情况下,cmd 应该去掉第一个和最后一个引号,否则将命令行解析为批处理文件中的一行。
      • 最终你最好使用subprocess.Popen 来解决这个问题。只需打开输出文件并运行将标准输出重定向到文件的基本命令,例如p = subprocess.Popen(cmd, stdout=output.fileno()).
      猜你喜欢
      • 1970-01-01
      • 2018-03-14
      • 2020-06-08
      • 2018-01-30
      • 2010-10-29
      • 2017-07-04
      • 2013-07-06
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多