0

I have written this simple Python script that finds the current date and time:

import subprocess 
time = subprocess.Popen('date')
print 'It is ', str(time)

When I run the program, I get the following:

It is  <subprocess.Popen object at 0x106fe6ad0>
Tue May 24 17:55:45 CEST 2016

How can I get rid of this part in the output? <subprocess.Popen object at 0x106fe6ad0>

On the other hand, if I use call(), as follows:

from subprocess import call 
time = call('date')
print 'It is ', str(time)

I get:

Tue May 24 17:57:29 CEST 2016
It is  0

How can I get the Tue May 24 17:57:29 CEST 2016 come in place of 0. And, why do we get 0 in the first hand?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

2

All you really need for a simple process such as calling date is subprocess.check_output. I pass in a list out of habit in the example below but it's not necessary here since you only have a single element/command; i.e. date.

time = subprocess.check_output(['date'])

or simply

time = subprocess.check_output('date')

Putting it together:

import subprocess
time = subprocess.check_output(['date'])
print 'It is', time

The list is necessary if you have multiple statement such as the executable name followed by command line arguments. For instance, if you wanted date to display the UNIX epoch, you couldn't pass in the string "date +%s" but would have to use ["date", "+%s"] instead.

jDo
  • 3,962
  • 1
  • 11
  • 30
1

You need to use communicate and PIPE to get the output:

import subprocess 

time = subprocess.Popen('date', stdout=subprocess.PIPE, stderr=subprocess.PIPE)

output, errors = time.communicate()

print ('It is ', output.decode('utf-8').strip())

With subprocess.call(), 0 is the return value. 0 means that there was no error in executing the command.

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
  • Thanks for your reply. The output using your script is: ('It is ', u'Tue May 24 18:20:05 CEST 2016'). Why do I get the 'u'? – Simplicity May 24 '16 at 16:20
  • I believe the "print" statement can be simply be as follows? print 'It is', output – Simplicity May 24 '16 at 16:29
  • @Simplicity the 'u' means [unicode](http://stackoverflow.com/questions/2464959/whats-the-u-prefix-in-a-python-string) – Farhan.K May 25 '16 at 19:53