问题
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