user3227965
user3227965

Reputation: 23

Python with subprocess

I am trying to learn Python, using Python 2.6. This is my first script:

#!usr/bin/python
import subprocess

command = subprocess.Popen(['date'])
print command.communicate()

It works and prints the date, however it seems to print (None, None) as below:

[root@localhost ~]# python tester.py
Thu Apr 17 14:03:00 BST 2014
(None, None)
[root@localhost ~]#

How can I make it not print that, and just print the date.

Upvotes: 0

Views: 263

Answers (3)

SethMMorton
SethMMorton

Reputation: 48815

When you call date, it just prints it's output to the terminal. That's the first line of output you were seeing. To not see the (None, None), you can modify your code to not include the print statement.

#!usr/bin/python
import subprocess

command = subprocess.Popen(['date'])
command.communicate()

This will give you the output you want. Possibly an easier method would be

#!usr/bin/python
import subprocess

subprocess.call(['date'])

If you want to collect the output yourself and possibly use it, you can use

#!usr/bin/python
import subprocess

output = subprocess.check_output(['date'])
print output

In general, you probably get away with using subprocess.call or subprocess.check_output instead of subprocess.Popen; Popen will work, but it is overkill in many situations.

Upvotes: 0

lvc
lvc

Reputation: 35089

By default when you call Popen, the subprocess inherits Pythons standard streams (stdin, stdout and stderr). So, stdout will be the terminal, and date will echo straight to it. You can see this by comment out your print and noticing that the date still gets printed. To have the stdout echo into a Python string instead, pass the special value subprocess.PIPE to use as stdout:

command = subprocess.Popen(['date'], stdout=subprocess.PIPE)
print command.communicate()

and you will get something like this:

('Thu Apr 17 23:11:16 EST 2014\n', None)

the remaining None is the stderr of the subprocess - you can also set it to PIPE, in which case it would be an empty string (unless date does print something to stderr). But to get just the stdout, you can use command.communicate()[0].


Two side notes: first, it would be a good idea to upgrade your Python if you can. Most new programs should probably use Python 3, but if you must use Python 2, at least use 2.7 rather than 2.6. More importantly, it is a really bad idea to run things as root if you don't have to - and in this case, you really don't (and if you ever do, you should set up your program so it only uses root when it needs to).

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363807

You need to set the subprocess up for communication:

>>> from subprocess import Popen, PIPE
>>> command = Popen(['date'], stdout=PIPE)
>>> command.communicate()
('do apr 17 15:06:16 CEST 2014\n', None)

The first part of the return value is stdout, the second is stderr.

Upvotes: 4

Related Questions