简体   繁体   English

如何从Python中的Shell脚本导入变量?

[英]How to import variable from Shell script in Python?

I have a Shell script, lets call it file.sh , that identifies a variable LOGFILE .我有一个 Shell 脚本,我们称之为file.sh ,它标识一个变量LOGFILE I am trying to run a Python script calling the same variable, however it is not exporting properly.我正在尝试运行调用相同变量的 Python 脚本,但它没有正确导出。

I tried:我试过了:

import os
print(os.environ(LOGFILE))

and got this error: name 'LOGFILE' is not defined并收到此错误: name 'LOGFILE' is not defined

They are in the same directory, so I am not sure what the error is?它们在同一个目录中,所以我不确定错误是什么? How can I fix this?我怎样才能解决这个问题?

The environment variable is not directly accessible as python variable.环境变量不能作为 python 变量直接访问。 This is why you need to pass the name of the external environment-variable in the form of a string.这就是为什么您需要以字符串形式传递外部环境变量的名称。 Furthermore, environ is not a function, it is a dictionary, so you need to use square brackets to lookup 'LOGFILE' in the dictionary:此外,environ 不是 function,它是一个字典,因此您需要使用方括号在字典中查找“LOGFILE”:

print(os.environ['LOGFILE'])

If you want a function that does something similar, use os.getenv()如果你想要一个 function 做类似的事情,使用 os.getenv()

print(os.getenv('LOGFILE'))

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

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