在IPython中cd vs!cd vs%cd

时间:2016-04-09 03:48:41

标签: 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

正如您所看到的,我实际上并没有更改目录;仅在IPython shell中。我认为这是因为我没有在IPython中使用!cd,但这也不起作用:

$ 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

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

1 个答案:

答案 0 :(得分:12)

!command没有制作" shell"运行命令。它使 a shell运行该命令。它不是你运行IPython的shell;你不能从IPython向该shell发送命令。它是一个新的外壳。

执行!cd时,启动一个新的shell,它会更改自己当前的工作目录并立即关闭。这对IPython或你从中启动IPython的shell没有影响。

执行cd%cd时,告诉IPython更改自己的工作目录。这将在您的IPython会话期间持续存在,但它仍然对您启动IPython的shell没有影响。当你停止IPython时,那个shell仍然会在你启动IPython时的任何目录中。

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