0

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?

asked Mar 4, 2016 at 0:21

1 Answer 1

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'])
answered Mar 4, 2016 at 0:58
Sign up to request clarification or add additional context in comments.

7 Comments

I was hoping to get the advantages of the IPython magic, but in a script form... is there any reason that this sort of thing should be available in a shell but not a script?
I don't have any experience with this but have you tried importing IPython? My understanding is that these functions are part of IPython so if you are not in that environment then you don't have access to them.
Just tried that and it had no effect. I assumed that because I am selecting IPython as the interpreter it would be doing this anyway...
I've never seen it done in the manner you describe. That would be cool. But perhaps they wouldn't be called "magic" anymore!!
I'm not sure I'm understanding the difference... what's the difference between typing lines into an IPython shell manually, and IPython reading those same lines from a file?
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.