子进程中'shell = True'的实际含义

Actual meaning of #39;shell=True#39; in subprocess(子进程中shell = True的实际含义)

本文介绍了子进程中'shell = True'的实际含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 subprocess 模块调用不同的进程.不过,我有一个问题.

I am calling different processes with the subprocess module. However, I have a question.

在以下代码中:

callProcess = subprocess.Popen(['ls', '-l'], shell=True)

callProcess = subprocess.Popen(['ls', '-l']) # without shell

两者都有效.阅读文档后,我知道 shell=True 意味着通过 shell 执行代码.这意味着在缺席的情况下,直接启动该过程.

Both work. After reading the docs, I came to know that shell=True means executing the code through the shell. So that means in absence, the process is directly started.

那么对于我的情况,我应该更喜欢什么 - 我需要运行一个进程并获取它的输出.从 shell 内部或外部调用它有什么好处.

So what should I prefer for my case - I need to run a process and get its output. What benefit do I have from calling it from within the shell or outside of it.

推荐答案

不通过 shell 调用的好处是您不会调用神秘程序".在 POSIX 上,环境变量 SHELL 控制调用哪个二进制文件作为shell".在 Windows 上,没有 bourne shell 后代,只有 cmd.exe.

The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable SHELL controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe.

因此调用 shell 会调用用户选择的程序,并且是平台相关的.一般来说,避免通过 shell 调用.

So invoking the shell invokes a program of the user's choosing and is platform-dependent. Generally speaking, avoid invocations via the shell.

通过 shell 调用确实允许您根据 shell 的通常机制扩展环境变量和文件 glob.在 POSIX 系统上,shell 将文件 glob 扩展为文件列表.在 Windows 上,无论如何,shell 不会扩展文件 glob(例如,*.*")(但命令行上的环境变量由 cmd.exe 扩展).

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., "*.*") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

如果您认为您需要环境变量扩展和文件 glob,请研究 1992 年对通过 shell 执行子程序调用的网络服务的 ILS 攻击.示例包括涉及 ILS 的各种 sendmail 后门.

If you think you want environment variable expansions and file globs, research the ILS attacks of 1992-ish on network services which performed subprogram invocations via the shell. Examples include the various sendmail backdoors involving ILS.

总之,使用 shell=False.

这篇关于子进程中'shell = True'的实际含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:子进程中'shell = True'的实际含义

基础教程推荐