Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking shell-command from function in interactive IPython shell

I have just been playing around with IPython. Currently I am wondering how it would be possible to run a shell-command with a python variable within a function. For example:

def x(go):
    return !ls -la {go}

x("*.rar")

This gives me "sh: 1: Syntax error: end of file unexpected". Could anybody please give me a clue on how to let my "x"-function invoke ls like "ls -la *.rar"? There are *.rar files in my working directory.

Thank you in advance, Rainer

like image 753
dubbaluga Avatar asked May 20 '26 09:05

dubbaluga


2 Answers

If you look at the history command output, you'll see that to call external programs ipython uses _ip.system method.

Hence, this should work for you:

def x(go):
    return _ip.system("ls -la {0}".format(go))

However, please note that outside ipython you should probably use subprocess.Popen.

like image 138
jcollado Avatar answered May 22 '26 21:05

jcollado


There was a bug in the "!" shell access that made the expansion of "function scoped variables" fail. Your ipython's version might be affected.

You can avoid it by doing yourself the variable expansion:

def x(go):
    return get_ipython().getoutput("ls -la {0}".format(go))
like image 28
barracel Avatar answered May 22 '26 23:05

barracel