想在python脚本里面source .profile,调用os.system后在当前运行的脚本里环境变量没有变呢?求解决方法。

2024-11-05 21:45:35
推荐回答(3个)
回答(1):

因为你调用os.system执行source .profile命令是在子进程中进行的,不能改变python当前进程的环境变量。

你应该修改os.environ。
一个mapping对象表示环境。例如,os.environ['HOME'] ,表示的你自己home文件夹的路径(某些平台支持,windows不支持)
,它与C中的getenv("HOME")一致。

回答(2):

在Python中环境变量的正确获取方法应该是os.environ返回的是个dict类型的数据

回答(3):

source is not an executable command, it's a shell builtin.
The most usual case for using source is to run a shell script that changes the environment and to retain that environment in the current shell. That's exactly how virtualenv works to modify the default python environment.
Creating a sub-process and using source in the subprocess probably won't do anything useful, it won't modify the environment of the parent process, none of the side-effects of using the sourced script will take place.
Python has an analogous command, execfile, which runs the specified file using the current python global namespace (or another, if you supply one), that you could use in a similar way as the bash command source.
https://stackoverflow.com/questions/7040592/calling-the-source-command-from-subprocess-popen