I have some lines of python code that I’m continuously copying/pasting into the python console. Is there a load command or something I can run? e.g. load file.py
回答 0
对于Python 2(请参阅Python 3的其他答案),请尝试一下:
execfile('file.py')
用法示例:
C:\junk>copy con execfile_example.py
a =[9,42,888]
b = len(a)^Z
1 file(s) copied.
C:\junk>\python27\python
Python2.7.1(r271:86832,Nov272010,18:30:46)[MSC v.150032 bit (Intel)] on win32
Type"help","copyright","credits"or"license"for more information.>>> execfile('execfile_example.py')>>> a
[9,42,888]>>> b
3>>>
For Python 2 (see other answers for Python 3) give this a try:
execfile('file.py')
Example usage:
C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
1 file(s) copied.
C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>
-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function – and promoted the exec statement to a builtin universal function. As the comment in Python 3.0’s changelog and Hi-Angels comment suggest:
Open command prompt in the folder in which you files to be imported are present. when you type ‘python’, python terminal will be opened. Now you can use
I find myself frequently using Python’s interpreter to work with databases, files, etc — basically a lot of manual formatting of semi-structured data. I don’t properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) — some history of the interactive session? If I use something like script I get too much stdout noise. I don’t really need to pickle all the objects — though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn’t need. Is there a package that does this, or a DIY approach?
UPDATE: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:
IPython — should have been using this for ages, kind of what I had in mind
reinteract — very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: http://www.reinteract.org/trac/wiki/GettingIt . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.
bpython — extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.
I am converted, these really fill a need between interpreter and editor.
IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number).
Furthermore, the documentation states:
This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.
This allows for example, to reference older sessions, such as
# Add auto-completion and a stored history file of commands to your Python# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is# bound to the Esc key by default (you can change it - see readline docs).## Store the file in ~/.pystartup, and set an environment variable to point# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.## Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the# full path to your home directory.import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")def save_history(historyPath=historyPath):import readline
readline.write_history_file(historyPath)if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)del os, atexit, readline, rlcompleter, save_history, historyPath
There is a way to do it. Store the file in ~/.pystartup…
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
and then set the environment variable PYTHONSTARTUP in your shell (e.g. in ~/.bashrc):
export PYTHONSTARTUP=$HOME/.pystartup
You can also add this to get autocomplete for free:
readline.parse_and_bind('tab: complete')
Please note that this will only work on *nix systems. As readline is only available in Unix platform.
After installing Ipython, and opening an Ipython session by running the command:
ipython
from your command line, just run the following Ipython ‘magic’ command to automatically log your entire Ipython session:
%logstart
This will create a uniquely named .py file and store your session for later use as an interactive Ipython session or for use in the script(s) of your choosing.
There is %history magic for printing and saving the input history (and optionally the output).
To store your current session to a file named my_history.py:
>>> %hist -f my_history.py
History IPython stores both the commands you enter, and the results it produces. You can easily go through previous commands with the up- and down-arrow keys, or access your history in more sophisticated ways.
You can use the %history magic function to examine past input and output. Input history from previous sessions is saved in a database, and IPython can be configured to save output history.
Several other magic functions can use your input history, including %edit, %rerun, %recall, %macro, %save and %pastebin. You can use a standard format to refer to lines:
%pastebin 3 18-20 ~1/1-5
This will take line 3 and lines 18 to 20 from the current session, and lines 1-5 from the previous session.
See %history? for the Docstring and more examples.
Also, be sure to explore the capabilities of %store magic for lightweight persistence of variables in IPython.
Stores variables, aliases and macros in IPython’s database.
d = {'a': 1, 'b': 2}
%store d # stores the variable
del d
%store -r d # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}
To autorestore stored variables on startup, specifyc.StoreMagic.autorestore = True in ipython_config.py.
$ cat typescript
Script started on Sat14May201608:30:08 AM MDT
Python2.7.6(default,Jun222015,17:58:13)[GCC 4.8.2] on linux2
Type"help","copyright","credits"or"license"for more information.>>>print'Hello Pythonic World'HelloPythonicWorld>>>Scriptdone on Sat14May201608:30:42 AM MDT
As far as Linux goes, one can use script command to record the whole session. It is part of util-linux package so should be on most Linux systems . You can create and alias or function that will call script -c python and that will be saved to a typescript file. For instance, here’s a reprint of one such file.
$ cat typescript
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>>
Script done on Sat 14 May 2016 08:30:42 AM MDT
Small disadvantage here is that the script records everything , even line-feeds, whenever you hit backspaces , etc. So you may want to use col to clean up the output (see this post on Unix&Linux Stackexchange) .
The %history command is awesome, but unfortunately it won’t let you save things that were %paste ‘d into the sesh. To do that I think you have to do %logstartat the beginning (although I haven’t confirmed this works).
What I like to do is
%history -o -n -p -f filename.txt
which will save the output, line numbers, and ‘>>>’ before each input (o, n, and p options). See the docs for %history here.
If you use bpython, all your command history is by default saved to ~/.pythonhist.
To save the commands for later reusage you can copy them to a python script file:
$ cp ~/.pythonhist mycommands.py
Then edit that file to clean it up and put it under Python path (global or virtual environment’s site-packages, current directory, mentioning in *.pth, or some other way).
To include the commands into your shell, just import them from the saved file:
Some comments were asking how to save all of the IPython inputs at once. For %save magic in IPython, you can save all of the commands programmatically as shown below, to avoid the prompt message and also to avoid specifying the input numbers.
currentLine = len(In)-1
%save -f my_session 1-$currentLine
The -f option is used for forcing file replacement and the len(IN)-1 shows the current input prompt in IPython, allowing you to save the whole session programmatically.
For those using spacemacs, and ipython that comes with python-layer, save magic creates a lot of unwanted output, because of the constant auto-completion command working in the backround such as:
I’d like to suggest another way to maintain python session through tmux on linux. you run tmux, attach your self to the session you opened (if not attached after opening it directly). execute python and do whatever you are doing on it. then detach from session. detaching from a tmux session does not close the session. the session remains open.
pros of this method:
you can attach to this session from any other device (in case you can ssh your pc)
cons of this method:
this method does not relinquish the resources used by the opened python session until you actually exist the python interpreter.
In XWindows, run iPython from the Xfce terminal app
click Terminal in the top menu bar and look for save contents in the dropdown
I find this saves the input and output, going all the way back to when I opened the terminal. This is not ipython specific, and would work with ssh sessions or other tasks run from the terminal window.