Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())?

like image 526
Walrus the Cat Avatar asked Aug 05 '26 00:08

Walrus the Cat


2 Answers

There are three options for the standard Python interpreter:

  • python -i setup.py, as explained in tzaman's answer
  • dropping into interactive mode from within setup.py, as explained in Jordan P's answer
  • setting the environment variable PYTHONSTARTUP=setup.py.

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.

like image 195
abarnert Avatar answered Aug 06 '26 13:08

abarnert


In addition to the other answer, you can explicitly drop into interactive mode like this:

// setup.py
import code, datetime
today = datetime.datetime.today()
code.interact(local=locals())

execute normally

python setup.py
like image 38
Jordan P Avatar answered Aug 06 '26 12:08

Jordan P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!