Python 子进程在命令字符串中使用 \ 执行命令
Python subprocess execute command with \ in command string
我正在编写一个简单的程序,它接收命令行字符串并执行它。
示例命令行字符串可以是 dir "c:\users\xxx\My Documents"
由于“\”,我在尝试执行此操作时遇到了问题。我指定了一个目录名称作为其中包含反斜杠的字符串的示例。
因为我收到的命令可以是任何东西——比如正则表达式等,所以应该保留 \。我如何确保用户输入与在 python 脚本中输入的一样?
import platform
import subprocess
import sys
if __name__ == '__main__':
command = sys.argv[0].split()
if platform.system().lower() == 'windows':
runShell = True
out = subprocess.Popen(command,shell=runShell,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for line in out.stdout.readlines():
print line.strip()
所以我找到了关于如何解析作为字符串提供给 py 模块的 shell 命令的答案。
使用shlex模块-https://docs.python.org/2/library/shlex.html将命令str拆分成一个列表,可以用subprocess.Popen方法执行。
我正在编写一个简单的程序,它接收命令行字符串并执行它。
示例命令行字符串可以是 dir "c:\users\xxx\My Documents"
由于“\”,我在尝试执行此操作时遇到了问题。我指定了一个目录名称作为其中包含反斜杠的字符串的示例。
因为我收到的命令可以是任何东西——比如正则表达式等,所以应该保留 \。我如何确保用户输入与在 python 脚本中输入的一样?
import platform
import subprocess
import sys
if __name__ == '__main__':
command = sys.argv[0].split()
if platform.system().lower() == 'windows':
runShell = True
out = subprocess.Popen(command,shell=runShell,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for line in out.stdout.readlines():
print line.strip()
所以我找到了关于如何解析作为字符串提供给 py 模块的 shell 命令的答案。
使用shlex模块-https://docs.python.org/2/library/shlex.html将命令str拆分成一个列表,可以用subprocess.Popen方法执行。