【问题标题】:Difference between shell=True or False in python subprocess [duplicate]python子进程中shell = True或False之间的区别[重复]
【发布时间】:2016-11-19 10:03:59
【问题描述】:

我刚开始使用 python 子进程模块。

代码subprocess.call("ls", shell = False) and subprocess.call("ls", shell = True) 都返回相同的结果。我只是想知道这两个 shell 选项的主要区别是什么。

【问题讨论】:

    标签: python python-2.7 subprocess


    【解决方案1】:

    Straight out of the Docs:

    如果 shell 为 True,指定的命令将通过 shell 执行。如果您将 Python 主要用于它在大多数系统 shell 上提供的增强控制流,并且仍然希望方便地访问其他 shell 功能,例如 shell 管道、文件名通配符、环境变量扩展和 ~ 到用户家的扩展,这将很有用目录。但是,请注意 Python 本身提供了许多类似 shell 的功能的实现(特别是 glob、fnmatch、os.walk()、os.path.expandvars()、os.path.expanduser() 和 shutil)。

    这可以将您的代码打开到 shell 注入技术,这里可以更好地解释:

    Shell Injection Shell=True

    例如,在 windows 机器上,如果 shell 设置为 false,请参见下文:

    import subprocess
    
    subprocess.Popen("dir", shell = False)
    

    运行时,此代码将返回一个WindowsError: [Error 2],说明找不到指定的文件。但是,如果 shell 为 True,则应返回一个对象。这是因为'dir' 正在通过 cmd 进行“管道传输”,因此,诸如 dir 之类的内置命令将起作用。

    同样适用于 subprocess.call。

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 1970-01-01
      • 2016-12-02
      • 2019-12-12
      • 2012-08-23
      • 2010-10-11
      • 2018-04-16
      • 2017-03-01
      相关资源
      最近更新 更多