使用\ in命令字符串的Python子进程执行命令

时间:2015-02-03 11:00:16

标签: python command-line

我正在编写一个简单的程序,它接受一个命令行字符串并执行它。

示例命令行字符串可以是dir“c:\ users \ xxx \ My Documents”

由于'\',我无法尝试执行此操作。我已经指定了一个dir名称作为其中包含反斜杠的字符串的示例。

由于我收到的命令可能是任何东西 - 比如正则表达式等,所以应该维护\。我如何确保用户输入保持在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()

1 个答案:

答案 0 :(得分:0)

所以我找到了关于如何将作为字符串提供的shell命令解析为py模块的答案。

使用shlex模块 - https://docs.python.org/2/library/shlex.html将命令str拆分为可由subprocess.Popen方法执行的列表。