简体   繁体   English

我们可以在python中运行ipython命令吗?

[英]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. 假设我想使用jupiter notebook / ipython作为开发环境,然后将所有内容复制到python脚本中。 In ipython we have commands like 在ipython中我们有像这样的命令

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. 假设我完成了我的ipython笔记本并希望复制所有内容(假设我有1000行,我无法逐个编辑它们)来创建我的python脚本。 Is it possible to enable my python script to understand such lines like "cd .." etc. 是否有可能使我的python脚本能够理解像“cd ..”等行。

Any method for running your IPython code using a standard Python interpreter is going to be a little complicated. 使用标准 Python解释器运行IPython代码的任何方法都会有点复杂。 For example, see this question, with one of the answers illustrating the call to IPython's 'magic' methods to do a shell command: 例如,看到这个问题,其中一个答案说明了调用IPython的'魔术'方法来执行shell命令:

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. 更容易的选择是简单地使用IPython解释器来运行您保存的脚本。 You need to make sure that each shell command is preceded by a % , as this indicates a 'magic' command. 您需要确保每个shell命令前面都有% ,因为这表示“魔术”命令。 Should be a simple find-and-replace task, as I doubt you are using too many shell commands. 应该是一个简单的查找和替换任务,因为我怀疑你使用了太多的shell命令。 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. 如果有许多不同的shell命令以%为前缀,您还可以编写一个简短的脚本来为您完成此工作。 You also need to ensure that your script has the extension .ipy . 您还需要确保您的脚本具有扩展名.ipy

script.ipy: script.ipy:

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

To run script from terminal: 从终端运行脚本:

>>> ipython script.ipy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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