如何在python中读取设置环境变量 [英] How to read set environment variable in python

查看:111
本文介绍了如何在python中读取设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UNIX命令行中,我这样做

In UNIX from command line, I do

setenv HOME <path to home>

我将其作为参数传递给python脚本

I pass it as argument to my python script

 python hello.py HOME

然后做

sys.argv[1] = os.environ["HOME"] 

它仍然不读取路径.

我是python的新手,在这种情况下 os.environ 是否正确?

I am new to python, is os.environ correct for this case?

推荐答案

如果您的目的是获取主目录的路径作为参数,则可以通过在调用脚本之前让Shell对参数进行评估来使用户发送它

If your aim is to get the path of the home directory as argument, you can just make your user send it by making shell evaluate the argument before calling the script.

我有一个简单的脚本,例如-

I have a simple script like -

import sys
print(sys.argv[1])

在Windows中,我将其称为-

In Windows I call it as -

set HOME=D:\
python script.py %HOME%

我得到的输出是-

D:\

在Linux中-

$ python hello.py $HOME

输出-

/home/random/

如果要从环境变量中获取它,并希望将环境变量传递为脚本的第一个参数,则应像-

If you want to get it from the environment variable, and you want to pass the environment variable to use as the first argument to the script, then you should change your script like -

sys.argv[1] = os.environ.get(sys.argv[1],sys.argv[1])

这样

这篇关于如何在python中读取设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆