Run IPython in a script

2019-09-01 04:42发布

问题:

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