Heisenberg
Heisenberg

Reputation: 8816

What is the best way to organize my local python scripts?

I have a bunch of useful scripts that I want to import from time to time. How to best organize them? I would want them to be on my /home/ folder -- is that possible? Is that the best way?

On a related note, when my other scripts import my local scripts, is there a best practice to make them portable? Should I include notes in my script to alert readers / myself that I'm importing from self-written script?

Thank you!

Upvotes: 3

Views: 1797

Answers (1)

Remco Haszing
Remco Haszing

Reputation: 7819

In your .bashrc you can specify the $PYTHONSTARTUP and $PYTHONPATH parameters. I have the following in my own .bashrc:

export PYTHONSTARTUP=$HOME/.config/python/pythonrc.py
export PYTHONPATH=$PYTHONPATH:$HOME/.config/python/path

Note that The .bashrc file is for bash specifically. Other shells may have other files loaded at startup.

The $PYTHONSTARTUP script is run every time you start a python console. This is useful if you want to add tab completion for example. For example in the case I specified, whenever you run python from the terminal, the script .config/python/pythonrc.py is executed before the console starts.

You can put python packages which should be importable anywhere in the $PYTHONPATH you specified. So basically $PYTHONPATH for python has some similarities to $PATH for bash. Note this is not $PATH. I do not recommend messing with the $PYTHONPATH though. I think it is better to append the paths to sys.path in the $PYTHONSTARTUP script.

And then there is the usercustomize module. If there is a module named usercustomize anywhere in the path, it will be imported by all python processes. For usercustomize to work you do need to make sure that this is in your $PYTHONPATH. For usercustomize you do need to set it in $PYTHONPATH, but you could append more paths in usercustomize.py just like in $PYTHONSTARTUP, so you only need to add 1 more directory to the $PYTHONPATH.

Upvotes: 3

Related Questions