英文:
Get the a variable defined in the command running python
问题
我有一个名为test.py的脚本:
import os
print(os.environ['LOL'])
我是这样运行它的:
> (LOL=HAHAHA; python3 test.py)
但是它引发了一个KeyError,因为它找不到变量LOL。
我还尝试过:
os.getenv('LOL')
但它只返回None。
在这种情况下,我如何访问变量LOL。
英文:
I have this script named test.py:
import os
print(os.environ['LOL'])
That I run as follow :
> (LOL=HAHAHA; python3 test.py)
But it raises a KeyError because it can't find the variable LOL.
I also tried with :
os.getenv('LOL')
But it just returns None.
How can I access to the variable LOL in this context.
答案1
得分: 1
你正在尝试访问一个环境变量,所以如果你在Windows上要设置它,你需要像这样做:
set LOL=HAHAHAHA
然后你应该能够访问它。为了确保它被正确设置,你也可以运行:
set
以获取完整的环境变量列表。
英文:
You are trying to access an environmental variable, so if you are on windows to set it you need to do something like:
set LOL=HAHAHAHA
Then you should be able to access it. To make sure it was set correctly you can also just run:
set
To get a full list of environmental variables.
答案2
得分: 1
您需要在调用python3 test.py
命令期间为环境变量提供补充,如下所示:
$ LOL=HAHAHA python3 test.py
HAHAHA
$ env LOL=HAHAHA python3 test.py
HAHAHA
$ echo $LOL
<empty string>
或者您可以为当前会话导出变量:
$ export LOL=HAHAHA
$ python3 test.py
HAHAHA
$ echo $LOL
HAHAHA
请注意,只使用LOL=HAHAHA; python3 test.py
不起作用,因为它仅为shell进程设置了LOL=HAHAHA
变量。
还要注意,第一种方法仅为特定命令设置环境变量,不会设置到环境中。而使用导出则会将其设置为环境变量。您可以在上面的$LOL
值中看到这两种方法的不同。
英文:
You need to supplement the environment variables for the command during which you invoke python3 test.py
as follows
$ LOL=HAHAHA python3 test.py
HAHAHA
$ env LOL=HAHAHA python3 test.py
HAHAHA
$ echo $LOL
<empty string>
or you can export the variable for the current session as:
$ export LOL=HAHAHA
$ python3 test.py
HAHAHA
$ echo $LOL
HAHAHA
Simply doing LOL=HAHAHA; python3 test.py
doesn't work because that just sets the LOL=HAHAHA
variable for the shell process.
Another thing to note, the first approach shown only sets the environment variable for that specific command. It does not set it in the environment. Doing it with the export instead, sets it for the environment. You can see the difference in the values of $LOL
above
答案3
得分: 1
只导出变量,即运行以下命令:
export LOL=HAHA; python3 test.py
或在同一命令中设置LOL
,即不带分号:
LOL=HAHA python3 test.py
test.py
的内容:
import os
print(os.environ['LOL'])
英文:
Just export the variable, i.e. run the command with:
export LOL=HAHA; python3 test.py
or set LOL
in the same command, i.e. without the semicolon:
LOL=HAHA python3 test.py
Content of test.py
:
import os
print(os.environ['LOL'])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论