在 Python 中读写环境变量?

Reading and writing environment variables in Python?(在 Python 中读写环境变量?)

本文介绍了在 Python 中读写环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 python 脚本调用了许多 python 函数和 shell 脚本.我想在 Python(主调用函数)和所有子进程(包括 shell 脚本)中设置环境变量以查看环境变量集.

My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.

我需要像这样设置一些环境变量:

I need to set some environmental variables like this:

DEBUSSY 1
FSDB 1

1 是一个数字,而不是一个字符串.此外,如何读取存储在环境变量中的值?(就像另一个 python 子脚本中的 DEBUSSY/FSDB.)

1 is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like DEBUSSY/FSDB in another python child script.)

推荐答案

尝试使用 os 模块.

import os

os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'

# Open child processes via os.system(), popen() or fork() and execv()

someVariable = int(os.environ['DEBUSSY'])

请参阅 os.environ<上的 Python 文档/代码>.此外,有关生成子进程的信息,请参阅 Python 的 子进程文档.

See the Python docs on os.environ. Also, for spawning child processes, see Python's subprocess docs.

这篇关于在 Python 中读写环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Python 中读写环境变量?

基础教程推荐