我正在尝试通过子进程来运行一个命令行命令,该命令接收作为参数文件。但是,这些文件可能具有类似“&”的字符,如果它们不在引号(“)之间,则可以将它们解释为CMD命令。
它通常可以正常工作,并且我在列表中打断了命令。示例:
from subprocess import run
file = r'broken&difficult.txt'
command = ['convert', file]
run(command)
但是它将返回一个stdErr:
StdErr: 'diffcult.txt' is not recognized as an internal or external command, operable program or batch file
返回码为1。
我已尝试将文件名变量更改为:
file =r'"broken&difficult.txt"'
结果是它找不到任何文件。返回码为0
您需要在&符之前使用CMD转义字符-胡萝卜^
-。
尝试:
import subprocess
file = 'broken^&difficult.txt'
command = ['convert', file]
subprocess.run(command, shell=True)