Ask Your Question
2

Calling Unix shell command as an expression

asked 2010-08-25 03:31:48 +0100

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

process_local_directory_for_something(!pwd)

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
4

answered 2010-08-25 03:52:20 +0100

William Stein gravatar image

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

sage: os.popen('pwd').read()
'/Users/wstein\n'

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 os.open('...').read(), and is implemented using subprocess. I don't think this currently exists.

edit flag offensive delete link more

Comments

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

John Palmieri gravatar imageJohn Palmieri ( 2010-08-25 11:45:58 +0100 )edit
3

answered 2010-08-25 14:45:38 +0100

mhampton gravatar image

updated 2010-08-25 14:46:09 +0100

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')
'/Users/mh\n'
edit flag offensive delete link more

Comments

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 19:03:34 +0100 )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

Stats

Asked: 2010-08-25 03:31:48 +0100

Seen: 1,043 times

Last updated: Aug 25 '10