简体   繁体   English

如何在 python 中使用同一 shell 中的脚本导出环境变量?

[英]How do I export environment variables using a script in the same shell in python?

My django project fetches credentials from environment variables, now I want to automate this process and store the credentials in the vault(hashivcorp).我的 django 项目从环境变量中获取凭据,现在我想自动化这个过程并将凭据存储在保险库(hashivcorp)中。 I have a python and shell script which fetches data from an API and exports it as environment variables, when I run it using os.system command it runs the shell script but as it runs it in a subprocess, I can't access the variables in the main(parent) process/shell. I have a python and shell script which fetches data from an API and exports it as environment variables, when I run it using os.system command it runs the shell script but as it runs it in a subprocess, I can't access the variables在主(父)进程/外壳中。 Only way of doing it by inserting the shell script in the settings.py file.唯一的方法是在 settings.py 文件中插入 shell 脚本。 Is there any way I can do it so that I get those in the main process?有什么办法可以让我在主流程中得到这些吗? Ps: I did try sourcing, os.system didn't recognise it as a command. Ps:我确实尝试过采购,os.system 没有将其识别为命令。

Here's the code I'm running:这是我正在运行的代码:

import os

os.environ['ENV'] = 'Demo'
os.system('python3 /home/rishabh/export.py')

print(os.environ.get('RDS_DB_NAME'))

output: output:

None

the python file, shell script works just fine. python 文件,shell 脚本工作得很好。

One way to do it is to run export.py in the same process, as user1934428 suggested:一种方法是在同一进程中运行export.py ,正如user1934428建议的那样:

import os
import sys

os.environ['ENV'] = 'Demo'

sys.path.append('/home/rishabh/')
import export   # runs export.py in the same process

print(os.environ.get('RDS_DB_NAME'))

This assumes there are no __name__ == '__main__' checks inside export.py .这假设 export.py 中没有export.py __name__ == '__main__'检查。

You only need the sys.path line if export.py is in a different directory than your current script.如果export.py与当前脚本位于不同的目录中,则只需要sys.path行。

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

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