Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run python command line interpreter with imports loaded automatically

Tags:

I would like to play around in the python interpreter but with a bunch of imports and object setup completed. Right now I'm launching the interpreter on the command line and doing the setup work every time. Is there any way to launch the command line interpreter with all the initialization work done?

Ex:

# Done automatically. import foo import baz l = [1,2,3,4] # Launch the interpreter. launch_interpreter() >> print l >> [1,2,3,4] 
like image 818
stackOverlord Avatar asked Feb 23 '12 08:02

stackOverlord


People also ask

How do I automatically import a Python package?

Automatically add import statementsIn the Settings/Preferences dialog ( Ctrl+Alt+S ), click Editor | General | Auto Import. In the Python section, configure automatic imports: Select Show import popup to automatically display an import popup when tying the name of a class that lacks an import statement.

How do I run an imported Python script?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run Python interpreter from command line?

Windows: type "powershell" in the lower left, this opens the Windows command line terminal. In the terminal type the command "python3" ("python" on Windows, or sometimes "py"). This runs the interpreter program directly. On the Mac type ctrl-d to exit (on Windows ctrl-z).

Why is Python running my module when I import it?

This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .


1 Answers

You can create a script with the code you wish to run automatically, then use python -i to run it. For example, create a script (let's call it script.py) with this:

import foo import baz l = [1,2,3,4] 

Then run the script

$ python -i script.py >>> print l [1, 2, 3, 4] 

After the script has completed running, python leaves you in an interactive session with the results of the script still around.

If you really want some things done every time you run python, you can set the environment variable PYTHONSTARTUP to a script which will be run every time you start python. See the documentation on the interactive startup file.

like image 193
srgerg Avatar answered Nov 11 '22 13:11

srgerg