Ask Your Question

Calling Unix shell command as an expression

asked 2010-08-24 20:31:48 -0500

jsrn gravatar image

Can I call a Unix shell command from within Sage as an expression? For example, I might want to do something like


Unfortunately, the !-operator does _very_ weird things when used as an expression (bug?), so the above doesn't work. The os.system() does not work either (it returns the return code instead of the output). Of course, Python has options, like handling pipes or subprocesses, but for many applications this is a bit tedious.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2010-08-24 20:52:20 -0500

William Stein gravatar image

I often use os.popen to solve exactly this problem:

sage: os.popen('pwd').read()

Big Caveat: Note that according to the Python docs, os.popen is deprecated and one is supposed to use subprocess.Popen as explained here. However, if you look at the examples using subprocess.Popen to do the same as what you can do using os.popen, you see that using subprocess.Popen makes the code often twice as long and complicated. This sucks. I think it would be good to add a new command to Sage that works much like'...').read(), and is implemented using subprocess. I don't think this currently exists.

edit flag offensive delete link more


You can use `Popen('pwd', stdout=PIPE).communicate()[0]` (after `from subprocess import *`).

John Palmieri gravatar imageJohn Palmieri ( 2010-08-25 04:45:58 -0500 )edit

answered 2010-08-25 07:45:38 -0500

mhampton gravatar image

updated 2010-08-25 07:46:09 -0500

Subprocess is somewhat baroque, but you could make a convenience function and put it in your init.sage file, e.g.:

import subprocess
def make_it_so(acommand):
    Uses subprocess module to return the output of a shell command
    return subprocess.Popen(acommand,shell=True,stdout=subprocess.PIPE).communicate()[0]

and then

sage: make_it_so('pwd')
edit flag offensive delete link more


That will work fine for a simple command with no options, but what if acommand has options, e.g., 'ls -l'??

William Stein gravatar imageWilliam Stein ( 2010-08-25 12:03:34 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2010-08-24 20:31:48 -0500

Seen: 514 times

Last updated: Aug 25 '10