subprocess.call(['source', '/etc/profile']) File "/usr/lib64/python2.7/subprocess.py", line 524, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
时间: 2024-04-15 10:27:35 浏览: 386
subprocess.call(['source', '/etc/profile'])
这行代码会导致 OSError: [Errno 2] No such file or directory
错误,因为 source
命令不是一个可执行的程序,它是在当前的环境中运行的。在 Python 的 subprocess
模块中,call
函数只能执行可执行程序,而不能直接执行 shell 命令。
如果你希望在 Python 中执行类似于 source /etc/profile
的操作,可以使用 subprocess.Popen
来启动一个新的 shell 进程,并在该进程中执行命令。下面是一个示例代码:
import subprocess
# 执行 source /etc/profile
subprocess.Popen(["/bin/bash", "-c", "source /etc/profile"])
# 或者使用以下方法
# subprocess.Popen(["/usr/bin/env", "bash", "-c", "source /etc/profile"])
# 建议在子进程中执行其他命令,以确保环境变量已经生效
subprocess.call(["command1"])
subprocess.call(["command2"])
上面的代码使用 subprocess.Popen
启动一个新的 Bash 进程,并在该进程中执行 source /etc/profile
命令。请注意,/bin/bash
是 Bash Shell 的路径,你可能需要根据你的系统进行调整。使用这种方法,你可以确保环境变量已经生效,然后可以在子进程中执行其他命令。
相关推荐



















