2016-03-04 108 views
0

我正在尝试使用IPython做一些脚本,但是我发现它在脚本中的行为与我运行交互式shell时的行为非常不同。在脚本中运行IPython

例如,我可以运行交互式以下几点:

In [1]: %profile 
default 

In [2]: ls/
bin/ cdrom/ etc/ [email protected]  lib/ lib64/  media/ opt/ root/ sbin/ sys/ usr/ [email protected] 
boot/ dev/ home/ [email protected] lib32/ lost+found/ mnt/ proc/ run/ srv/ tmp/ var/ [email protected] 

In [3]: mkdir tmpdir 

In [4]: cd tmpdir 
/home/alex/tmp/tmpdir 

没问题。

然而,当我在脚本中运行它们没有这些命令的工作原理:

#!/usr/bin/ipython3 

%profile 
ls/
mkdir tmpdir 
cd tmdir 

我得到一个错误:

$ ./tmp.py 
    File "/home/alex/tmp/tmp.ipython", line 3 
    %profile 
    ^
SyntaxError: invalid syntax 

我试图通过运行这个:

  1. 直接调用文件如上,
  2. 明确地调用它的机智^ h IPython的:`ipython3 tmp.py”
  3. 传递-i--profile=sh论点IPython中
  4. 调用它时,改变文件扩展.ipython.ipy到IPython的

我的问题: 为什么它在shell脚本中的行为有所不同?我如何让IPython在脚本中运行这些命令?

回答

1

它们的工作原因是IPython magic,但它们是shell命令,不能在Python中工作。让他们考虑subprocess library。如果在shell命令中使用空格,而在列表中使用逗号分隔的值。

import subprocess 
subprocess.check_call(['ls']) 
subprocess.check_call(['ls', '-a']) 
+0

我曾希望得到IPython魔术的优点,但是在一个脚本形式中......是否有任何理由认为这种事情应该在shell而不是脚本中可用? – Alex

+0

我没有任何经验,但你有没有尝试[导入IPython](http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding)?我的理解是,这些函数是IPython的一部分,所以如果你不在那个环境中,那么你不能访问它们。 – Mark

+0

刚刚尝试过,它没有效果。我认为,因为我选择IPython作为解释器,它会这样做...... – Alex