3

How do I make a blocking operating system call in python?

For example get the output of the linux "date" command.

And put its string output result into a string variable.


Dear Stackoverflow.

What is unclear about "operating system call"

What is unclear about "blocking"

I suspect the people who "close" do not even read the question.

Is there a procedure for unblocking questions?

SHernandez
  • 1,060
  • 1
  • 14
  • 21

3 Answers3

3

You can do something like this:

import subprocess
proc = subprocess.Popen(['date'],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

The first argument to Popen is the list of command line arguments you'd like executed. The PIPE arguments which follow instruct python to capture the output of the command. communicate() waits for the command to complete and returns the stdout and stderr of the process as strings. After execution, the stdout variable will contain the text from the subprocess. Note that there are a few caveats to this pattern (particularly with large amounts of output). You can learn more here:

https://docs.python.org/2/library/subprocess.html

matthewatabet
  • 1,463
  • 11
  • 26
  • This is a very good answer but F.X.'s way is more convenient and also handles errors and exceptions nice. Will probably have to accept his – SHernandez Jul 12 '15 at 19:30
  • @SHernandez -- That's true, but it is not available in all versions of python. The code I work with generally requires the lowest common denominator. So, I generally use the less-convenient approach and error catch where needed. The very best solution will depend upon your use case. – matthewatabet Jul 12 '15 at 19:33
  • It should be noted that stdout and stderr in the last line are bytestrings with a newline at the end. But the same name parameters to the function calls are operating system pipe objects, just to prevent confusion – SHernandez Jul 12 '15 at 19:34
2

To get the output of a command, use check_output, which has the advantage over Popen that it raises an exception if the command fails :

from subprocess import check_output
output = check_output(["date"])

(I assumed that you're not talking about real system calls.)

F.X.
  • 6,809
  • 3
  • 49
  • 71
1

You can call:

import os

os.system('date')
Ming
  • 1,613
  • 12
  • 27