【问题标题】:cd vs !cd vs %cd in IPythonIPython 中的 cd vs !cd vs %cd
【发布时间】:2016-04-09 03:48:40
【问题描述】:

我认为在 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 也没有更改目录;但我本来希望实际的外壳会这样做。最后,使用魔术命令%cdcd 具有相同的效果。那么,这三者有什么区别,我如何才能真正告诉系统 shell 在 IPython 中执行命令呢?

【问题讨论】:

    标签: python ipython


    【解决方案1】:

    !command 不会让“shell”运行命令。它使 a shell 运行命令。这不是你运行 IPython 的 shell;你不能从 IPython 向那个 shell 发送命令。这是一个新的外壳。

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

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

    您不能从 IPython 更改父 shell 的工作目录。

    【讨论】:

    • "您不能从 IPython 更改父 shell 的工作目录。" - 或者实际上,在 POSIX 模型中。可能有一些非常骇人听闻的方法来实现这一点,例如ptrace(2),但我不建议尝试。
    • 那么cd%cd有什么区别?
    • @Alexey:它们是等价的,除非您关闭 automagic 设置,在这种情况下,cd 只是尝试引用名为 cd 的变量。
    • 好的,谢谢。如果您将此添加到您的答案中可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-08-22
    • 2023-02-01
    • 2023-01-11
    • 2014-05-19
    • 2017-12-06
    • 2010-10-09
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多