providernomad.blogg.se

Python subprocess get output line by line
Python subprocess get output line by line












python subprocess get output line by line

In Python Subprocess Module, we can take the output from an executed command and make it as input for another command, using the input parameter. If you start notepad.exe as a windowed app then python will not get the output. Input Parameter in Python Subprocess Run Function. () () print "Waiting for process to exit." returnCode = process.wait() if returnCode != 0: raise subprocess.CalledProcessError(returnCode, command) sleep(0.05) print "Waiting for async readers to finish." stdoutReader.join() stderrReader.join() # Close subprocess' file descriptors. # Sleep for a short time to avoid excessive CPU use while waiting for data. import subprocess task subprocess.Popen('cat file.txt', shellTrue, stdoutsubprocess. Now, I want to use subprocess to read the output of cat tabdelimited1.txt. In the command line, cat tabdelimited1.txt will output all of the lines. while not stderrQueue.empty(): line = stderrQueue.get() print 'Received stderr: ' + repr(line) # Do stuff with stderr line. However, let's say we wanted to use subprocess. # Process all available lines from the stderr Queue. while not stdoutQueue.empty(): line = stdoutQueue.get() print 'Received stdout: ' + repr(line) # Do stuff with stdout line. while not stdoutReader.eof() or not stderrReader.eof(): # Process all available lines from the stdout Queue. Если кто-то хочет читать как stdout и stderr в то же время, используя потоки, это то, что я придумал: import threading import subprocess import Queue class AsyncLineReader(threading.Thread): def _init_(self, fd, outputQueue): threading.Thread._init_(self) assert isinstance(outputQueue, Queue.Queue) assert callable(fd.readline) self.fd = fd self.outputQueue = outputQueue def run(self): map(, iter(self.fd.readline, '')) def eof(self): return not self.is_alive() and () def getForFd(cls, fd, start=True): queue = Queue.Queue() reader = cls(fd, queue) if start: reader.start() return reader, queue process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdoutReader, stdoutQueue) = AsyncLineReader.getForFd(process.stdout) (stderrReader, stderrQueue) = AsyncLineReader.getForFd(process.stderr) # Keep checking queues until there is no more output.














Python subprocess get output line by line