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

In the following codes:

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

and

callProcess = subprocess.Popen(['ls', '-l']) # without 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.

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.

推荐答案

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.

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

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).

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.

In summary, use shell=False.

Python相关问答推荐

使用@ guardlasses. guardlass和注释的Python继承

Polars:用氨纶的其他部分替换氨纶的部分

使用groupby Pandas的一些操作

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

如何在表中添加重复的列?

如何在Python请求中组合多个适配器?

Python 3试图访问在线程调用中实例化的类的对象

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,

为用户输入的整数查找根/幂整数对的Python练习

如何在Python中自动创建数字文件夹和正在进行的文件夹?

如何将一个文件的多列导入到Python中的同一数组中?

具有不同坐标的tkinter canvs.cocords()和canvs.moveto()

pyspark where子句可以在不存在的列上工作

如何有效地计算所有输出相对于参数的梯度?

将多行数据循环到嵌套框架中的单行

如何强制SqlalChemy指向与连接字符串的默认架构不同的架构

Python-迭代PANAS中的数据框并替换列表中不包含字符串的值

使用Python下载pdf url

使用Numpy进行重写For循环矢量化