gpt4 book ai didi

python - 如何让 python 程序监听环境变量?

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:34 25 4
gpt4 key购买 nike

抱歉,如果这个问题不清楚。

我用 python 写了一个库,要上传到 PyPI (pip)。我想让我的程序运行并响应环境变量的输入。

例如引用这个库: https://github.com/rg3/youtube-dl

通过pip安装后,用户可以直接通过pip调用程序。

$ pip install youtube-dl
$ youtube-dl http://youtube.com/video?v=sdfafd7f6s

# What's cool is that the above even works in a virtualenv!

我也喜欢将我的程序放在环境变量中,但我不确定如何设置它。

有什么线索吗?谢谢!

最佳答案

你的问题不清楚。看起来你想要的是从命令行运行你的程序而不显式调用 Python 解释器。

为此,您只需要在您的setup.py 中添加几行代码来声明一个entry point。 .这在 Automatic Script Creation 中有解释。 .基本上,您需要一个 console_scripts 项目:

setup(
# other arguments here...
entry_points = {
'console_scripts': ['foo = my_package.some_module:main_func']
}
)

您可以在 setup.py file for youtube-dl 的第 68-71 行看到类似的内容.

如果你真的想读取环境变量,使用environ来自 os 模块。

import os

try:
important_info = os.environ['IMPORTANT_INFO']
except KeyError:
raise Exception('Set IMPORTANT_INFO environment variable, please!')

关于python - 如何让 python 程序监听环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com