سؤال

Sorry if this question is unclear.

I wrote a library in python, to be uploaded to PyPI (pip). I'd like to have my program run and respond to inputs on an environment variable.

For example, refer to this library: https://github.com/rg3/youtube-dl

After installing it via pip, users can instantly call upon the program via.

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

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

I'd also love for my program to be put on an environment variable, but i'm not sure how to set this up.

Any clues? Thanks!

هل كانت مفيدة؟

المحلول

Your question is unclear. It looks like what you want is to run your program from the command line without explicitly invoking the Python interpreter.

To do this, you just need a few lines in your setup.py to declare an entry point. That is explained in Automatic Script Creation. Basically, you need a console_scripts item:

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

You can see something similar in lines 68-71 of the setup.py file for youtube-dl.

If you really want to read environment variables, use environ from the os module.

import os

try:
    important_info = os.environ['IMPORTANT_INFO']
except KeyError:
    raise Exception('Set IMPORTANT_INFO environment variable, please!')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top