简体   繁体   中英

Could we run ipython commands in python?

Suppose I want use jupiter notebook/ipython as an development environment and copy everything to a python scripts afterwards. In ipython we have commands like

In [1]: cd ..
/Users/myname/Desktop/software

In [2]: ls
  blah_blah_blah/ 

Suppose I finish my ipython notebook and want to copy everything (suppose I have 1000 lines and I could not edit them 1 by 1) to create my python script. Is it possible to enable my python script to understand such lines like "cd .." etc.

Any method for running your IPython code using a standard Python interpreter is going to be a little complicated. For example, see this question, with one of the answers illustrating the call to IPython's 'magic' methods to do a shell command:

from IPython.terminal.embed import InteractiveShellEmbed

ipshell = InteractiveShellEmbed()
ipshell.dummy_mode = True
ipshell.magic("%timeit abs(-42)")

The much easier option would be to simply use the IPython interpreter to run your saved script. You need to make sure that each shell command is preceded by a % , as this indicates a 'magic' command. Should be a simple find-and-replace task, as I doubt you are using too many shell commands. If there are a lot of different shell commands to prefix with % you could also write a short script to do this work for you. You also need to ensure that your script has the extension .ipy .

script.ipy:

%cd ..
%ls
x = "My script!"
print(x)

To run script from terminal:

>>> ipython script.ipy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM