Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get terminal output in python? [duplicate]

I can execute a terminal command using os.system() but I want to capture the output of this command. How can I do this?

like image 338
AssemblerGuy Avatar asked Dec 10 '10 11:12

AssemblerGuy


People also ask

How do I copy a terminal output?

CTRL+V and CTRL-V in the terminal. You just need to press SHIFT at the same time as CTRL : copy = CTRL+SHIFT+C. paste = CTRL+SHIFT+V.

How do I copy a terminal output in Linux?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do you get the output code in Python?

In Python 3. x, you can output without a newline by passing end="" to the print function or by using the method write: import sys print("Hello", end="") sys. stdout.


1 Answers

>>> import subprocess >>> cmd = [ 'echo', 'arg1', 'arg2' ] >>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0] >>> print output arg1 arg2 

There is a bug in using of the subprocess.PIPE. For the huge output use this:

import subprocess import tempfile  with tempfile.TemporaryFile() as tempf:     proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)     proc.wait()     tempf.seek(0)     print tempf.read() 
like image 92
Jiří Polcar Avatar answered Sep 29 '22 06:09

Jiří Polcar