Initialize an interpreter with variables

How to initialize python interpreter so that it already has variables in its memory? For example, how could I initialize the [ni] Python interpreter and enter as my first input:

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

without a name binding str(today = datetime.datetime.today())?

+2
source share
4 answers

If you are using ipython, you can configure it to automatically load scripts.

Run

$ ipython profile create

which will create a default profile in your home directory.

Create a file named ~/.ipython/ipython_init.pyand add

import datetime
today = datetime.datetime.today

Now at the end ~/.ipython/profile_default/ipython_config.pyadd this line so that it loads this file every time the interpreter starts

c.InteractiveShellApp.exec_files = ['~/.ipython/ipython_init.py']

, ipython, .

In [1]: today
Out[1]: datetime.datetime(2017, 3, 2, 13, 31, 26, 776744)
+1

script, "" , .

:

# foo.py
import datetime
today = datetime.datetime.today

:

python -i foo.py
>>> today
'2015-05-05 17:49:32.726496'

, IPython . IPython , :

In [1]: %run foo.py

script , , .

+2

:

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

python setup.py
+2

Python:

, Python . export PYTHONSTARTUP=setup.py , , setup.py. , , , ( Windows System Control Panel - ).

PYTHONSTARTUP virtualenvwrapper post_activate. hook export PYTHONSTARTUP=${VIRTUAL_ENV}/setup.py, .

, -i, , PYTHONSTARTUP .


IPython has its very powerful (but somewhat complicated) configuration and configuration system . You can create a dozen different profiles and edit each of them to enable and disable use -iand PYTHONSTARTUP, change PYTHONSTARTUPto use a different variable name, execute different lines of code each time the kernel starts, and so on. Most of what you want is under IPython Terminal Settings if you use it on a terminal.

+2
source

All Articles