在Python中读写环境变量?
我的 python 脚本调用了许多 python 函数和 shell 脚本。我想在Python(主调用函数)和所有子进程(包括shell脚本)中设置一个环境变量来查看环境变量集。
我需要设置一些环境变量,如下所示:
DEBUSSY 1
FSDB 1
1
是一个数字,而不是字符串。另外,如何读取存储在环境变量中的值? (就像另一个 python 子脚本中的 DEBUSSY
/FSDB
一样。)
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
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用 os 模块。
请参阅
os.environ
上的 Python 文档 。另外,有关生成子进程的信息,请参阅 Python 的子进程文档。Try using the
os
module.See the Python docs on
os.environ
. Also, for spawning child processes, see Python's subprocess docs.首先,读书是解决问题的优秀方法;这是权宜之计和解决问题的长期投资之间的区别。千万不要错过任何学习的机会。 :D
您可能选择将
1
解释为数字,但环境变量并不关心。它们只是传递字符串:(来自
environ(3posix)
。)您可以使用
os.environ
类似字典的对象:First things first :) reading books is an excellent approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might choose to interpret the
1
as a number, but environment variables don't care. They just pass around strings:(From
environ(3posix)
.)You access environment variables in python using the
os.environ
dictionary-like object:如果要将全局变量传递到新脚本中,可以创建一个仅用于保存全局变量的 python 文件(例如 globals.py)。当您在子脚本顶部导入此文件时,它应该可以访问所有这些变量。
如果您正在写入这些变量,那么情况就不同了。这涉及到并发性和锁定变量,除非您愿意,否则我不会涉及这些内容。
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
使用 os.environ[str(DEBUSSY)] 进行读取和写入 (http://docs.python.org/library/os.html#os.environ)。
至于读取,当然你必须自己从字符串中解析数字。
Use
os.environ[str(DEBUSSY)]
for both reading and writing (http://docs.python.org/library/os.html#os.environ).As for reading, you have to parse the number from the string yourself of course.