用python去修改linux環境變數為何無效

時間 2021-06-02 23:22:58

1樓:冒泡

環境變數是程序環境的屬性之一,當你用os.system去執行的時候,實際上是:

1 fork乙個子程序

2 子程序exec另乙個shell程式,執行你要執行的命令,比如你source,實際上是exec乙個shell程序再source,所以子程序的環境變數被你改了

但是你這個python程序不受任何影響

要修改當前程序的環境變數,用os.putenv,或操作os.environ這個字典(實際上並不是dict的直接例項,而是乙個用法和dict基本一樣的物件),這倆的區別參考os模組的文件

2樓:黃哥

答案在這裡

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.

用 execfile

學習Linux和Python去馬哥教育還是老男孩?

陳同學 首先,馬哥教育我沒有去過,我只去過老男孩。我相信,應該不會有人即去過馬哥,又去過老男孩,並同時去學習基礎吧。所以我只能說一下我自己去老男孩的感覺。首先老男孩是LINUX起家,如果是問LINUX培訓哪個更好,應該都不用猶豫,直接去老男孩肯定沒錯,鄙人有幸看過老男孩老師講的公開課,非常認可老男孩...

學習Python為啥要帶上Linux?

乙隻小恐龍 哇 不只是python,學啥都要帶上linux,我學swift的時候也順手帶上linux一起學得 linux是乙個工地,大家的生產環境都是上linux的乙隻小恐龍 ubuntu 倒逼你學習的系統 geek 應該反過來問學習linux 為什麼帶上py 因為py就是linux的潤滑油 lin...

如果要在 Linux 下學習 Python 語言,是不是最好裝雙系統?

黃哥 先安裝虛擬機器 virtualbox等 再在虛擬機上安裝ubuntu 等Linux。學習python php golang ruby最好是在Linux下學習。Python 初學者如何安裝VirtualBox 和Ubuntu。知乎專欄 1.Windows 2.Windows Linux虛擬機器 ...