6

With the following command, it prints '640x360'

>>> command = subprocess.call(['mediainfo', '--Inform=Video;%Width%x%Height%', 
'/Users/Desktop/1video.mp4'])

640x360

How would I set a variable equal to the string of the output, so I can get x='640x360'? Thank you.

David542
  • 104,438
  • 178
  • 489
  • 842
  • Answers should not be edited into the question. See [What is the appropriate action when the answer to a question is added to the question itself?](https://meta.stackoverflow.com/questions/267434/what-is-the-appropriate-action-when-the-answer-to-a-question-is-added-to-the-que) on [meta]. – Charles Duffy Sep 17 '18 at 01:36
  • Duplicate of https://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string – tripleee Oct 12 '21 at 11:01

2 Answers2

13

If you're using 2.7, you can use subprocess.check_output():

>>> import subprocess
>>> output = subprocess.check_output(['echo', '640x360'])
>>> print output
640x360

If not:

>>> p = subprocess.Popen(['echo', '640x360'], stdout=subprocess.PIPE)
>>> p.communicate()
('640x360\n', None)
Scott A
  • 7,745
  • 3
  • 33
  • 46
4
import subprocess
p = subprocess.Popen(["ls", "-al"], stdout=subprocess.PIPE)
out, err = p.communicate()
print out
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
  • I was just typing out the same answer, but just wanted to say that I'd suggest using Popen rather than call because it's slightly more explicit and does the same thing. subprocess.call is just a convenience function for Popen. – Vorticity Sep 09 '11 at 21:28
  • but call() prints the output and returns the exit code of your process, that is 0 if you process suceeded. – rocksportrocker Sep 09 '11 at 21:30
  • That's a good point that I had forgotten about. Given that, call() may be the better way to go in pre 2.7, but Scott Anderson's answer likely is better in 2.7 since it automatically checks for nominal exit status. – Vorticity Sep 09 '11 at 21:59