使用python通过文件设置环境变量 [英] set environment variables by file using python
本文介绍了使用python通过文件设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一组环境变量的文件.
I have a file contains set of environment variables .
env_script.env:
env_script.env:
export a=hjk
export b=jkjk
export c=kjjhh
export i=jkkl
..........
我想通过从file读取来设置这些环境变量. 我如何在python中做到这一点
I want set these environment variables by reading from file . how can i do this in python
尝试的示例代码:
pipe = subprocess.Popen([".%s;env", "/home/user/env_script.env"], stdout=subprocess.PIPE, shell=True)
output = pipe.communicate()[0]
env = dict((line.split("=", 1) for line in output.splitlines()))
os.environ.update(env)
请提出一些建议
推荐答案
您不需要使用子流程.
读取行并拆分环境变量名称,值并将其分配给os.environ
:
Read lines and split environment variable name, value and assign it to os.environ
:
import os
with open('/home/user/env_script.env') as f:
for line in f:
if 'export' not in line:
continue
if line.startswith('#'):
continue
# Remove leading `export `
# then, split name / value pair
key, value = line.replace('export ', '', 1).strip().split('=', 1)
os.environ[key] = value
或使用 dict.update
和生成器表达式:
with open('env_script.env') as f:
os.environ.update(
line.replace('export ', '', 1).strip().split('=', 1) for line in f
if 'export' in line
)
或者,您可以制作一个包装程序shell脚本(source
是env_script.env
),然后执行原始的python文件.
Alternatively, you can make a wrapper shell script, which source
s the env_script.env
, then execute the original python file.
#!/bin/bash
source /home/user/env_script.env
python /path/to/original_script.py
这篇关于使用python通过文件设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文