简体   繁体   中英

Adding a python script to the PATH environment variable when installing with pip

When installing django via pip, the PATH environment variable is modified to let the user access django-admin directly in the terminal. (django-admin startproject project_name)

I would like to the same for my pip package. I looked at how modifying environment variable using python but os.environ["PATH"] wont get saved once the python script is ended.

Any suggestion ?

The ideal way to do this is to give setuptools an Entry Point .

Instead of writing a script, you write a function in one of your modules.

For example, add this line to your setup call in setup.py :

entry_points = {
    'console_scripts': ['mytool'=mypkg.myscript:myfunc'],
}

… and setuptools will, at install time, automatically create a script named mytool that imports mypkg.myscript and calls its myfunc , all in a way that's appropriate for whatever Python installation the user used to pip install your package, and put mytool onto the user's PATH`.

This way, it takes care of all kinds of portability issues you never even thought of. What if the user is on Windows and their default Python is 2.7 but they used py -3 -m pip to install it? They'll get a file named mytool.py instead of mytool , and it'll have a Windows py -launcher-compatible shbang line, and it'll just work.


Occasionally, you can't reorganize things that way, and you have to manually write a script. In that case, just give setuptools the path to the script, by adding this argument to your setup call:

scripts=['bin/mytool']

setuptools can't do all of its magic here, but it can still get the script installed into the user's PATH .


Of course all of this depends on Python being set up properly. But however Python managed to put pip and django-admin on your PATH , then it will put your script on the PATH in the exact same way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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