Ask Your Question
2

Calling Unix shell command as an expression

asked 14 years ago

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.

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
4

answered 14 years ago

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.

Preview: (hide)
link

Comments

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

John Palmieri gravatar imageJohn Palmieri ( 14 years ago )
3

answered 14 years ago

mhampton gravatar image

updated 14 years ago

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'
Preview: (hide)
link

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 ( 14 years ago )

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: 14 years ago

Seen: 1,066 times

Last updated: Aug 25 '10