Cannot run escaped Windows command line on python

随声附和 提交于 2019-12-24 17:42:24

问题


When I run the following command on a Windows command prompt, no problem.

java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main

I tried running the command in a python script. It fails. My python script is like this;

import os
command_line = 'java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main'
os.system(command_line)

The error message received is

Error: Unable to access jarfile C:\Program Files (x86)\SnapBackuppp\snapbackup.jar

Can someone help? Thanks.

I am using python 2.7.9


回答1:


You are using backslashes in the command line. In python better use forward slashes or escape the backslashes with a backslash




回答2:


Try this:

command_line = 'java -jar "C:\\Program Files (x86)\\SnapBackup\\app\\snapbackup.jar" main'

Explanation

Windows uses backslashes ("\") instead of forward slashes ("/"). This isn't an issue when using the Windows command line itself, but causes problems when using other tools that process escape sequences. These escape sequences each start with a backslash. Typically, strings in Python process them.

https://docs.python.org/2/reference/lexical_analysis.html#string-literals

If you look closely at your error...

Error: Unable to access jarfile C:\Program Files (x86)\SnapBackuppp\snapbackup.jar

...you'll notice that it says SnapBackuppp, instead of SnapBackup\app

What happened?

The "\a" was being processed as the ASCII Bell (BEL) escape sequence (see link above). The other characters with a backslash in front of them weren't affected, because they don't correspond to an escape sequence. (That is, the \P in C:\Program Files (x86), etc.)

To avoid processing the \a as the Bell character, we need to escape the backslash itself, by typing \\a. That way, the second backslash is treated as a "normal" backslash, and the "a" gets read as expected.

You can also tell Python to use a raw (unprocessed) string by doing this:

command_line = r'java -jar "C:\Program Files (x86)\SnapBackup\app\snapbackup.jar" main'

(Note the r just before the first quote character.

Alternatively, you could also use forward slashes.

command_line = 'java -jar "C:/Program Files (x86)/SnapBackup/app/snapbackup.jar" main'

However, this may not work in all cases.




回答3:


You should probably use subprocess instead of os.system https://docs.python.org/2/library/subprocess.html. Also, like others before me have noted, you have unescaped backslashes. Use os.path.join to remedy the situation:

import subprocess, os
jarPath = os.path.join('c:', 'Program Files (x86)', 'SnapBackup', 'app', 'snapbackup.jar')
command_line = ['java', '-jar', jarPath, 'main']
subprocess.call(command_line)


来源:https://stackoverflow.com/questions/32448153/cannot-run-escaped-windows-command-line-on-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!