Python 的子进程模块中 PATH 的使用
Usage of PATH in Python's subprocess module
我偶然发现 Python 的 subprocess
模块有一个奇怪的行为:
>>> import os, subprocess
>>> del os.environ["PATH"]
>>> subprocess.run(["python", "--version"])
Python 3.5.1
CompletedProcess(args=['python', '--version'], returncode=0)
我想知道如何在未设置 PATH
环境变量的情况下 运行 命令?有没有默认的PATH
?
是的,有一个默认的PATH,至少在Linux。
参考 Linux execl() man page 中的这句话:
If [the PATH variable] isn't defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH). (This confstr(3) call typically returns the value "/bin:/usr/bin".)
The default search path used by exec*p*
and spawn*p*
if the
environment doesn’t have a 'PATH'
key. Also available via os.path
.
它在 posixpath.py
(os.path
on POSIX systems) and '.;C:\bin'
in ntpath.py
(os.path
on Windows) 中被硬编码为 ':/bin:/usr/bin'
。
我偶然发现 Python 的 subprocess
模块有一个奇怪的行为:
>>> import os, subprocess
>>> del os.environ["PATH"]
>>> subprocess.run(["python", "--version"])
Python 3.5.1
CompletedProcess(args=['python', '--version'], returncode=0)
我想知道如何在未设置 PATH
环境变量的情况下 运行 命令?有没有默认的PATH
?
是的,有一个默认的PATH,至少在Linux。
参考 Linux execl() man page 中的这句话:
If [the PATH variable] isn't defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH). (This confstr(3) call typically returns the value "/bin:/usr/bin".)
The default search path used by
exec*p*
andspawn*p*
if the environment doesn’t have a'PATH'
key. Also available viaos.path
.
它在 posixpath.py
(os.path
on POSIX systems) and '.;C:\bin'
in ntpath.py
(os.path
on Windows) 中被硬编码为 ':/bin:/usr/bin'
。