简体   繁体   English

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

[英]Load environment variables of bashrc into python

I'm trying to set the environment variable of my .bashrc using Spyder;我正在尝试使用 Spyder 设置我的.bashrc的环境变量; in other words I'm looking for a python command that reads my .bashrc .换句话说,我正在寻找一个读取我的.bashrc的 python 命令。 Any idea?任何的想法?

.bashrc should 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

The shell's startup file is the shell's startup file. shell的启动文件就是shell的启动文件。 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.您确实希望将事物解耦,以便 Python 不必了解 Bash 语法,并且您要从 Python 使用的设置不会隐藏在不同实用程序的整体启动文件中。

One way to solve this is to put your environment variables in a separate file, and source that file from your .bashrc .解决方法之一就是把你的环境变量在一个单独的文件,以及source从文件.bashrc Then when you invoke a shell from Python, that code can source the same file if it needs to.然后,当你调用从Python的外壳,该代码可以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',
    # Need a shell; need the shell to be Bash
    shell=True, executable='/bin/bash',
    # 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。 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM