Load environment variables of bashrc into python

自闭症网瘾萝莉.ら 提交于 2020-01-05 10:28:19

问题


I'm trying to set the environment variable of my .bashrc using Spyder; in other words I'm looking for a python command that reads my .bashrc. Any idea?


回答1:


.bashrc should automatically be loaded into the environ on login

import os

print os.environ

if you wanted to create a dictionary of values from a bash source file you could in theory do something like

output = subprocess.check_output("source /path/to/.bashrc;env")
env = dict(line.split("=") for line in output.splitlines() if "=" in line))
print env



回答2:


The shell's startup file is the shell's startup file. You really want to decouple things so that Python doesn't have to understand Bash syntax, and so that settings you want to use from Python are not hidden inside a different utility's monolithic startup file.

One way to solve this is to put your environment variables in a separate file, and source that file from your .bashrc. Then when you invoke a shell from Python, that code can source the same file if it needs to.

# .bashrc
source $HOME/lib/settings.sh

# Python >=3.5+ code
import subprocess
subprocess.run(
    'source $HOME/lib/settings.sh; exec the command you actually want to run',
    # basic hygiene
    check=True, universal_newlines=True)

(If you need to be compatible with older Python versions, try subprocess.check_call() or even subprocess.call() if you want to give up the safeguards by the check_ variant in favor of being compatible all the way back to Python 2.4.)



来源:https://stackoverflow.com/questions/27553576/load-environment-variables-of-bashrc-into-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!