http://wiki.crossplatform.ru/index.php?title=Python/FAQ/%D0%A3%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B8_%D0%B2%D0%B7%D0%B0%D0%B8%D0%BC%D0%BE%D0%B4%D0%B5%D0%B9%D1%81%D1%82%D0%B2%D0%B8%D0%B5_%D1%81_%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D1%81%D1%81%D0%B0%D0%BC%D0%B8&feed=atom&action=history
Python/FAQ/Управление и взаимодействие с процессами - История изменений
2024-03-29T05:46:48Z
История изменений этой страницы в вики
MediaWiki 1.15.1
http://wiki.crossplatform.ru/index.php?title=Python/FAQ/%D0%A3%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B8_%D0%B2%D0%B7%D0%B0%D0%B8%D0%BC%D0%BE%D0%B4%D0%B5%D0%B9%D1%81%D1%82%D0%B2%D0%B8%D0%B5_%D1%81_%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D1%81%D1%81%D0%B0%D0%BC%D0%B8&diff=3546&oldid=prev
Root: Новая: {{Python_header}} == 16. Process Management and Communication == == Gathering Output from a Program == <source lang="python"> import popen2 # other popen methods than popen4 can lead t...
2008-12-03T14:28:27Z
<p>Новая: {{Python_header}} == 16. Process Management and Communication == == Gathering Output from a Program == <source lang="python"> import popen2 # other popen methods than popen4 can lead t...</p>
<p><b>Новая страница</b></p><div>{{Python_header}}<br />
<br />
== 16. Process Management and Communication ==<br />
== Gathering Output from a Program ==<br />
<source lang="python"><br />
import popen2<br />
<br />
# other popen methods than popen4 can lead to deadlocks<br />
# if there is much data on stdout and stderr<br />
<br />
(err_out, stdin) = popen2.popen4("program args")<br />
lines = err_out.read() # collect output into one multiline string<br />
<br />
<br />
(err_out, stdin) = popen2.popen4("program args")<br />
lines = err_out.readlines() # collect output into a list, one line per element<br />
<br />
#-----------------------------<br />
<br />
(err_out, stdin) = popen2.popen4("program args")<br />
output = []<br />
while True:<br />
line = err_out.readline()<br />
if not line:<br />
break<br />
<br />
output.appen(line)<br />
output = ''.join(output)<br />
</source><br />
== Running Another Program ==<br />
<source lang="python"><br />
import os<br />
myfile = "foo.txt"<br />
status = os.system("vi %s" % myfile)<br />
<br />
#-----------------------------<br />
import os<br />
os.system("cmd1 args | cmd2 | cmd3 >outfile")<br />
os.system("cmd args <infile >outfile 2>errfile")<br />
<br />
status = os.system("%s %s %s" % (program, arg1, arg2))<br />
<br />
if status != 0:<br />
print "%s exited funny: %s" % (program, status)<br />
raise SystemExit<br />
<br />
</source><br />
== Replacing the Current Program with a Different One ==<br />
<source lang="python"><br />
# -----------------------------<br />
import os<br />
<br />
import sys<br />
import glob<br />
<br />
args = glob.glob("*.data")<br />
try:<br />
os.execvp("archive", args)<br />
except OSError, e:<br />
print "Couldn't replace myself with archive: %s" % err<br />
raise SystemExit<br />
<br />
# The error message does not contain the line number like the "die" in<br />
# perl. But if you want to show more information for debugging, you can<br />
# delete the try...except and you get a nice traceback which shows all<br />
# line numbers and filenames.<br />
<br />
# -----------------------------<br />
os.execvp("archive", ["accounting.data"])<br />
</source><br />
== Reading or Writing to Another Program ==<br />
<source lang="python"><br />
# -------------------------<br />
<br />
# Read from a child process<br />
<br />
import sys<br />
import popen2<br />
pipe = popen2.Popen4("program arguments")<br />
pid = pipe.pid<br />
for line in pipe.fromchild.readlines():<br />
sys.stdout.write(line)<br />
<br />
<br />
# Popen4 provides stdout and stderr.<br />
# This avoids deadlocks if you get data<br />
# from both streams.<br />
#<br />
# If you don't need the pid, you<br />
# can use popen2.popen4(...)<br />
<br />
# -----------------------------<br />
# Write to a child process<br />
<br />
<br />
import popen2<br />
<br />
pipe = popen2.Popen4("gzip > foo.gz")<br />
pid = pipe.pid<br />
pipe.tochild.write("Hello zipped world!\n")<br />
pipe.tochild.close() # programm will get EOF on STDIN<br />
<br />
</source><br />
== Filtering Your Own Output ==<br />
<source lang="python"><br />
class OutputFilter(object):<br />
def __init__(self, target, *args, **kwds):<br />
self.target = target<br />
self.setup(*args, **kwds)<br />
self.textbuffer = ""<br />
<br />
def setup(self, *args, **kwds):<br />
pass<br />
<br />
def write(self, data):<br />
if data.endswith("\n"):<br />
data = self.process(self.textbuffer + data)<br />
self.textbuffer = ""<br />
<br />
if data is not None:<br />
self.target.write(data)<br />
else:<br />
self.textbuffer += data<br />
<br />
def process(self, data):<br />
return data<br />
<br />
<br />
class HeadFilter(OutputFilter):<br />
def setup(self, maxcount):<br />
self.count = 0<br />
self.maxcount = maxcount<br />
<br />
def process(self, data):<br />
if self.count < self.maxcount:<br />
self.count += 1<br />
return data<br />
<br />
<br />
class NumberFilter(OutputFilter):<br />
def setup(self):<br />
self.count=0<br />
<br />
def process(self, data):<br />
self.count += 1<br />
return "%s: %s"%(self.count, data)<br />
<br />
<br />
class QuoteFilter(OutputFilter):<br />
def process(self, data):<br />
return "> " + data<br />
<br />
<br />
import sys<br />
f = HeadFilter(sys.stdout, 100)<br />
for i in range(130):<br />
print>>f, i<br />
<br />
print<br />
<br />
txt = """Welcome to Linux, version 2.0.33 on a i686<br />
<br />
"The software required `Windows 95 or better', <br />
so I installed Linux." """<br />
f1 = NumberFilter(sys.stdout)<br />
f2 = QuoteFilter(f1)<br />
for line in txt.split("\n"):<br />
print>>f2, line<br />
print<br />
f1 = QuoteFilter(sys.stdout)<br />
f2 = NumberFilter(f1)<br />
for line in txt.split("\n"):<br />
print>>f2, line<br />
</source><br />
== Preprocessing Input ==<br />
<source lang="python"><br />
# This script accepts several filenames<br />
# as argument. If the file is zipped, unzip<br />
# it first. Then read each line if the file<br />
import os<br />
import sys<br />
import popen2<br />
<br />
for file in sys.argv[1:]:<br />
if file.endswith(".gz") or file.endswith(".Z"):<br />
(stdout, stdin) = popen2.popen2("gzip -dc '%s'" % file)<br />
fd = stdout<br />
else:<br />
fd = open(file)<br />
for line in fd:<br />
# ....<br />
sys.stdout.write(line)<br />
fd.close()<br />
#-----------------------------<br />
<br />
#-----------------------------<br />
# Ask for filename and open it<br />
import sys<br />
print "File, please?"<br />
line = sys.stdin.readline()<br />
file = line.strip() # chomp<br />
open(file)<br />
</source><br />
== Reading STDERR from a Program ==<br />
<source lang="python"><br />
# Execute foo_command and read the output<br />
<br />
import popen2<br />
(stdout_err, stdin) = popen2.popen4("foo_command")<br />
for line in stdout_err.readlines():<br />
# ....<br />
</source><br />
== Controlling Input and Output of Another Program ==<br />
<source lang="python"><br />
# Open command in a pipe<br />
# which reads from stdin and writes to stdout<br />
<br />
import popen2<br />
pipe = popen2.Popen4("wc -l") # Unix command<br />
pipe.tochild.write("line 1\nline 2\nline 3\n")<br />
pipe.tochild.close()<br />
output = pipe.fromchild.read()<br />
</source><br />
== Controlling the Input, Output, and Error of Another Program ==<br />
<source lang="python"><br />
<br />
<br />
# popen3: get stdout and stderr of new process<br />
# Attetion: This can lead to deadlock,<br />
# since the buffer of stderr or stdout might get filled.<br />
# You need to use select if you want to avoid this.<br />
<br />
import popen2<br />
(child_stdout, child_stdin, child_stderr) = popen2.popen3(...)<br />
</source><br />
== Communicating Between Related Processes ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Making a Process Look Like a File with Named Pipes ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Sharing Variables in Different Processes ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Listing Available Signals ==<br />
<source lang="python"><br />
#<br />
# Print available signals and their value<br />
# See "man signal" "man kill" on unix.<br />
<br />
import signal<br />
for name in dir(signal):<br />
if name.startswith("SIG"):<br />
value = getattr(signal, name)<br />
print "%s=%s" % (name, value)<br />
</source><br />
== Sending a Signal ==<br />
<source lang="python"><br />
# You can send signals to processes<br />
# with os.kill(pid, signal)<br />
</source><br />
== Installing a Signal Handler ==<br />
<source lang="python"><br />
import signal<br />
<br />
def get_sig_quit(signum, frame):<br />
....<br />
<br />
signal.signal(signal.SIGQUIT, get_sig_quit) # Install handler<br />
<br />
signal.signal(signal.SIGINT, signal.SIG_IGN) # Ignore this signal<br />
signal.signal(signal.SIGSTOP, signal.SIG_DFL) # Restore to default handling<br />
</source><br />
== Temporarily Overriding a Signal Handler ==<br />
<source lang="python"><br />
# Example of handler: User must Enter Name ctrl-c does not help<br />
<br />
import sys<br />
import signal<br />
<br />
def ding(signum, frame):<br />
print "\aEnter your name!"<br />
return<br />
<br />
signal.signal(signal.SIGINT, ding)<br />
print "Please enter your name:"<br />
<br />
name = ""<br />
while not name:<br />
try:<br />
name = sys.stdin.readline().strip()<br />
except:<br />
pass<br />
<br />
print "Hello: %s" % name<br />
</source><br />
== Writing a Signal Handler ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Catching Ctrl-C ==<br />
<source lang="python"><br />
import signal<br />
<br />
# ignore signal INT<br />
signal.signal(signal.SIGINT, signal.SIG_IGN)<br />
<br />
# Install signal handler<br />
def tsktsk(signum, frame):<br />
print "..."<br />
<br />
signal.signal(signal.SIGINT, tsktsk)<br />
</source><br />
== Avoiding Zombie Processes ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Blocking Signals ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
== Timing Out an Operation ==<br />
<source lang="python"><br />
import signal<br />
<br />
def handler(signum, frame):<br />
raise "timeout"<br />
<br />
signal.signal(signal.SIGALRM, handler)<br />
<br />
try:<br />
signal.alarm(5) # signal.alarm(3600)<br />
<br />
# long-time operation<br />
while True:<br />
print "foo"<br />
<br />
signal.alarm(0)<br />
except:<br />
signal.alarm(0)<br />
print "timed out"<br />
else:<br />
print "no time out"<br />
</source><br />
== Program: sigrand ==<br />
<source lang="python"><br />
# @@INCOMPLETE@@<br />
# @@INCOMPLETE@@<br />
</source><br />
<br />
{{Python_Footer}}</div>
Root