Walrus the Cat Walrus the Cat -4 years ago 109
Python Question

Initialize interpreter with variables

How do I initialize the python interpreter such that it already has variables in its memory? For example, how could I initialize a[n i]Python interpreter, and type as my first input:

In [1]: today
Out[1]: '2015-05-05 17:49:32.726496'


without first binding the name
str(today = datetime.datetime.today())
?

Answer Source

There are three options for the standard Python interpreter:

That last one is useful if you want to start and stop Python hundreds of times. Just export PYTHONSTARTUP=setup.py and as long as you're in the same shell, it'll always load setup.py. Or, if you want it more permanent, put it in your profile (or Windows System Control Panel Environment Variables or whatever).

PYTHONSTARTUP is especially handy with virtualenvwrapper and its post_activate hook. Just set the hook to export PYTHONSTARTUP=${VIRTUAL_ENV}/setup.py and you can have a different setup for each environment.

In fact, what -i actually does is, in effect, override PYTHONSTARTUP with a one-time temporary value.


IPython has its own very powerful (but somewhat complicated) configuration and customization system. You can build a dozen different profiles, and edit each one to enable and disable the use of -i and PYTHONSTARTUP, change PYTHONSTARTUP to use a different variable name, execute various lines of code each time a kernel is started, and so on. Most of what you want is under Terminal IPython options, if you're using it at the terminal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download