Skip to main content
 首页 » 编程设计

python之为什么我在这里需要 shell=True 才能让 Python 的 subprocess.check_output 工作

2025年05月04日15xxx_UU

我有一个从 if-up 脚本运行的 python 脚本,当建立 PPP 连接时,该脚本由 Linux 上的 ppp 程序调用。 python 脚本基本上调用命令行程序,解析结果并返回它:

import subprocess 
 
result = subprocess.check_output(["fw_printenv", "serialnr"]) 
result = # some operation  
return result 

尽管当我从命令行(例如 python script.py)手动运行 python 脚本时这段代码可以 100% 正常工作,但当它由 PPP 从 if 运行时根本不起作用-向上。调用 subprocess.check_output 时引发异常:[Errno 2] No such file or directory: 'fw_printenv'。

只有将代码更改为:

result = subprocess.check_output("fw_printenv serialnr", shell=True) 

为什么?

请您参考如下方法:

来自subprocess documentation :

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).

环境变量是获取二进制文件路径所必需的(特别是 PATH,包含可能的路径,包括 unix 系统下的 /usr/bin/)。 否则,fw_printenv 可能是 accessed by absolute path .