在脚本中运行IPython [英] Run IPython in a script

查看:266
本文介绍了在脚本中运行IPython的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用IPython编写脚本,但我发现它在脚本中的行为与我运行交互式shell时的行为完全不同。

I am trying to do some scripting with IPython, but I am finding that it behaves very differently in a script to when I run an interactive shell.

例如,我可以交互式运行以下内容:

For example, I can run the following interactively:

In [1]: %profile
default

In [2]: ls /
bin/   cdrom/  etc/   initrd.img@      lib/    lib64/       media/  opt/   root/  sbin/  sys/  usr/  vmlinuz@
boot/  dev/    home/  initrd.img.old@  lib32/  lost+found/  mnt/    proc/  run/   srv/   tmp/  var/  vmlinuz.old@

In [3]: mkdir tmpdir

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

没问题。

但是,当我在脚本中运行它们时,这些命令都不起作用:

However, none of these commands works when I run them in a script:

#!/usr/bin/ipython3

%profile
ls /
mkdir tmpdir
cd tmdir

我收到错误:

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

我试过通过以下方式运行:

I have tried running this by:


  1. 如上所述直接调用文件,

  2. 使用ipython显式调用它: `ipython3 tmp.py'

  3. 传递 -i - profile = sh 使用ipython调用ipython的参数

  4. 将文件扩展名更改为 .ipython 。 ipy

  1. calling the file directly as above,
  2. calling it explicitly with ipython: `ipython3 tmp.py'
  3. passing the -i or --profile=sh arguments to ipython when calling it with ipython
  4. changing the file extension to .ipython and .ipy

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

My question: Why is it behaving differently in a script to the shell? How can I get IPython to run these commands in a script?

推荐答案

由于 IPython magic 但它们是shell命令,不适用于Python。让他们考虑 子流程图书馆。在shell命令中有空格的位置,而不是列表中的逗号分隔值。

They are working due to IPython magic but they are shell commands and do not work in Python. To get them consider the subprocess library. Where you would have spaces in a shell command instead have comma-separated values in the list.

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

这篇关于在脚本中运行IPython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆