带有os.system()的Python'source HOME/.bashrc' [英] Python 'source HOME/.bashrc' with os.system()
问题描述
我正在编写一个Python脚本(Linux),该脚本添加了 shell别名(将它们写了出来)到 HOME/.bash_aliases
).
I am writing a python script (Linux) that is adding some shell aliases (writes them to HOME/.bash_aliases
).
为了使别名在写入后立即可用,我应该发出以下内置的bash:
In order to make an alias available immediately after it was written I should issue the following bash built-in:
source HOME/.bashrc
source
是bash内置的,所以我不能:
source
is a bash built-in so I cannot just:
os.system(source HOME/.bashrc)
如果我尝试类似的操作:
If i try something like:
os.system('/bin/bash -c source HOME/.bashrc')
...将冻结脚本(就像正在等待某些内容一样).
...will freeze the script (just like is waiting for something).
有什么建议吗?
推荐答案
您想要的东西是不可能的.程序(您的脚本)无法修改调用者(您从中运行它的外壳)的环境.
What you want is not possible. A program (your script) cannot modify the environment of the caller (the shell you run it from).
另一种允许您完成一些操作的方法是使用bash函数编写该函数,该函数在同一进程中运行,并且可以修改调用方.请注意,在运行时进行采购可能会产生负面影响,具体取决于用户在其bashrc中拥有什么.
Another approach which would allow you to do something close is to write it in terms of a bash function, which is run in the same process and can modify the caller. Note that sourcing during runtime can have possible negative side-effects depending on what the user has in their bashrc.
这篇关于带有os.system()的Python'source HOME/.bashrc'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!