[Tutor] interacting with shell

Kirby Urner urnerk@qwest.net
Fri, 19 Apr 2002 00:05:59 -0400


On Thursday 18 April 2002 06:42 pm, Paul Tremblay wrote:
> I am wondering how (of if) you interact with shell commands in
> python. 

You can definitely do this.  Probably the easiest thing is
to construct the final form of the command using string
substitution Python's way, and write this to the shell.
The popen command returns the shell's output as if from
a file.  Example:

 Python 2.2 (#1, Feb 24 2002, 16:21:58)
 [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> f = os.popen("echo $PATH")
 >>> f.readlines() 
 ['/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/games:/home/kirby/bin:
 /usr/java/j2re1.4.0/bin:.\n']
 >>> f.close()

Another example:

 >>> f=os.popen('date; ls *.sh')
 >>> f.readlines()
 ['Fri Apr 19 00:00:31 EDT 2002\n', 'repl.sh\n', 'testfermat.sh\n']
 >>> f.close()

And one more:

 >>> f = os.popen("joe=`expr 2 + 2`; echo $joe")  # using back tics
 >>> f.readlines()  # echoes joe
 ['4\n']  
 >>> f.close()

Anyway, I think you get the idea.  

Kirby