0

Given this variables:

cardIP="00.00.00.00"
dir="D:\\TestingScript"
mainScriptPath='"\\\\XX\\XX\\XX\\Testing\\SNMP Tests\\Python Script\\MainScript.py"'

When using subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP) and print(mainScriptPath+" "+dir+" "+cardIP) I get this:

 "\\XX\XX\XX\Testing\SNMP Tests\Python Script\MainScript.py"  D:\TestingScript  00.00.00.00

which is what I wanted, OK.

But now, I want the 'dir' variable to be also inside "" because I am going to use dir names with spaces. So, I do the same thing I did with 'mainScriptPath':

cardIP="00.00.00.00"
dir='"D:\\Testing Script"'
mainScriptPath='"\\XX\\XX\\XX\\Testing\\SNMP Tests\\Python Script\\MainScript.py"'

But now, when I'm doing print(mainScriptPath+" "+dir+" "+cardIP) I get:

"\\XX\XX\XX\Testing\SNMP Tests\Python Script\MainScript.py"  "D:\Testing Script"  00.00.00.00

Which is great, but when executed in subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP) there is a failure with 'mainScriptPath' variable:

 '\\XX\XX\XX\Testing\SNMP' is not recognized as an internal or external command...

It doesn't make sense to me.
Why does it fail?

In addition, I tried also:

dir="\""+"D:\\Testing Script"+"\""

Which in 'print' acts well but in 'subprocess.call' raise the same problem.

(Windows XP, Python3.3)

4

1 回答 1

2

Use proper string formatting, use single quotes for the formatting string and simply include the quotes:

subprocess.call('cmd /c "{}" "{}" "{}"'.format(mainScriptPath, dir, cardIP))

另一种方法是传入参数列表并让 Python 为您处理引用:

subprocess.call(['cmd', '/c', mainScriptPath, dir, cardIP])

当第一个参数.call()是列表时,Python 使用在 Windows 上将参数序列转换为字符串部分中描述的过程。

在 Windows 上,args序列被转换为可以使用以下规则解析的字符串(对应于 MS C 运行时使用的规则):

  1. 参数由空格分隔,空格可以是空格,也可以是制表符。
  2. 用双引号括起来的字符串被解释为单个参数,无论其中包含什么空格。带引号的字符串可以嵌入到参数中。
  3. 前面有反斜杠的双引号被解释为文字双引号。
  4. 反斜杠按字面意思解释,除非它们紧跟在双引号之前。
  5. 如果反斜杠紧接在双引号之前,则每对反斜杠都被解释为文字反斜杠。如果反斜杠的数量是奇数,则最后一个反斜杠转义下一个双引号,如规则 3 中所述。

这意味着将参数作为序列传递会使 Python 担心正确转义参数的所有细节,包括处理嵌入的反斜杠和双引号。

于 2013-09-03T09:08:34.170 回答