Run IPython in a script

早过忘川 提交于 2019-12-12 03:25:05

问题


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

No problem.

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

#!/usr/bin/ipython3

%profile
ls /
mkdir tmpdir
cd tmdir

I get an error:

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

I have tried running this by:

  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

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?


回答1:


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'])


来源:https://stackoverflow.com/questions/35785742/run-ipython-in-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!