Python-Ref > System interaction > Running foreign programs > Working with programs IO
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Working with programs IO

How to run a foreign program, provide its standard input and capture its output directly.
From time to time it is important to be able to capture the output of a program directly. Sometimes it is even desirable to send it some data as standard input.
The following code sends a few lines to the program sort - standard unix program that sorts the lines of input. It then reads its output and prints it on the screen.
Expand/Shrink
Zdroj: (process2-1.py)
  1   import subprocess
  2   
  3   p = subprocess.Popen( "sort", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  4   print "just as test", p
  5   output, error = p.communicate( "hello\nhow\nare\nyou")
  6   print "---------"
  7   print "output", output
  8   print "error", error
stdout:
just as test <subprocess.Popen object at 0x7ffe76165c10>
---------
output are
hello
how
you

error None
Doba běhu: 28.7 ms
Expand/Shrink
Zdroj: (process2-2.py)
  1   import subprocess
  2   
  3   outfile = file("out.txt", "w")
  4   p = subprocess.Popen( "sort", stdin=subprocess.PIPE, stdout=outfile)
  5   p.communicate( "hello\nhow\nare\nyou")
  6   outfile.close()
are
hello
how
you
Doba běhu: 28.0 ms