在IPython中cd vs!cd vs%cd

bcf*_*bcf 5 python ipython

我认为!在IPython中添加一个shell命令会使系统shell实际执行命令,但似乎并非如此.考虑以下内容,我开始使用/home/Documents/Rx,启动IPython,使用命令cd(没有!),然后退出IPython并查看我所在的目录:

$ pwd
/home/Documents/Rx
$ ipython
Python 2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.3 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: cd Papers/
/home/Documents/Rx/Papers

In [2]: pwd
Out[2]: u'/home/Documents/Rx/Papers'

In [3]: exit()
$ pwd
/home/Documents/Rx
Run Code Online (Sandbox Code Playgroud)

如你所见,我实际上没有改变目录; 仅在IPython shell中.我以为这是因为我没有!cd在IPython中使用,但这不起作用:

$ pwd
/home/Documents/Rx
$ ipython
Python 2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.3 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: !cd Papers/

In [2]: pwd
Out[2]: u'/home/Documents/Rx'

In [3]: exit()
$ pwd
/home/Documents/Rx
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,IPython shell也没有更改目录; 但我本来期望实际的shell这样做.最后,使用magic命令%cd具有相同的效果cd.那么,这三者之间有什么区别,我怎样才能真正告诉系统shell在IPython中执行命令?

use*_*ica 13

!command不会让"shell"运行命令.它使一个外壳运行命令.这不是你运行IPython的shell; 你无法从IPython向该shell发送命令.这是一个新的外壳.

执行此操作时!cd,将启动一个新shell,该shell将更改其自己的当前工作目录并立即关闭.这对IPython或你启动IPython的shell没有影响.

当你这样做cd或者%cd,你告诉IPython的改变自己的工作目录.这将在您的IPython会话期间持续存在,但它仍然对您启动IPython的shell没有影响.当您停止IPython时,该shell仍将位于启动IPython时的任何目录中.

您无法从IPython更改父shell的工作目录.

  • @Alexey:它们是等效的,除非您关闭“automagic”设置,在这种情况下“cd”只是尝试引用名为“cd”的变量。 (3认同)