bash 将bashrc的环境变量加载到python中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27553576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:02:21  来源:igfitidea点击:

Load environment variables of bashrc into python

pythonbashenvironment-variablesspyder

提问by ChrisB

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

我正在尝试设置我.bashrc使用 Spyder的环境变量;换句话说,我正在寻找一个 python 命令来读取我的.bashrc. 任何的想法?

回答by Joran Beasley

.bashrcshould automatically be loaded into the environ on login

.bashrc登录时应自动加载到环境中

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

如果您想从 bash 源文件创建值字典,理论上您可以执行以下操作

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

回答by tripleee

The shell's startup file is the shell'sstartup 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.

shell的启动文件就是shell的启动文件。您确实希望将事物解耦,以便 Python 不必了解 Bash 语法,并且您要从 Python 使用的设置不会隐藏在不同实用程序的整体启动文件中。

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

解决此问题的一种方法是将您的环境变量放在一个单独的文件中,并将source该文件从.bashrc. 然后,当您从 Python 调用 shell 时,source如果需要,该代码可以使用相同的文件。

# .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.)

(如果您需要与较旧的 Python 版本兼容,请尝试subprocess.check_call()或什subprocess.call()至您想放弃check_变体的保护措施,以支持一直兼容到 Python 2.4。)