Python中解析路径时的奇怪问题

2024-06-25 22:51:55 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑到这些变量:

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

当使用subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP)print(mainScriptPath+" "+dir+" "+cardIP)时,我得到如下结果:

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

这正是我想要的,好吧。你知道吗

但是现在,我希望'dir'变量也在“”中,因为我要用dir名称加空格。 所以,我用“mainScriptPath”做了同样的事情:

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

但是现在,当我做print(mainScriptPath+" "+dir+" "+cardIP)时,我得到:

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

这很好,但在subprocess.call("cmd /c "+mainScriptPath+" "+dir+" "+cardIP)中执行时,“mainScriptPath”变量出现故障:

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

这对我来说毫无意义。
为什么会失败?你知道吗

此外,我还尝试:

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

在“印刷”中表现良好,但在“印刷”中子流程调用“提出同样的问题。你知道吗

(Windows XP、Python3.3)


Tags: pycmddirscripttestscalltestingsnmp
1条回答
网友
1楼 · 发布于 2024-06-25 22:51:55

使用正确的字符串格式,对格式字符串使用单引号,只需包含引号:

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

另一种方法是传入一个参数列表,并让Python负责引用:

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

.call()的第一个参数是一个列表时,Python使用Converting an argument sequence to a string on Windows节中描述的过程。你知道吗

On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):

  1. Arguments are delimited by white space, which is either a space or a tab.
  2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.
  3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
  4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
  5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.

这意味着以序列形式传入参数会让Python担心正确转义参数的所有细节,包括处理嵌入的反斜杠和双引号。你知道吗

相关问题 更多 >