Cannot run escaped Windows command line on python

2019-08-05 23:21发布

问题:

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)