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.

1
  • unrelated: import time; print(time.ctime()) Commented May 25, 2016 at 19:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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'?
I believe the "print" statement can be simply be as follows? print 'It is', output
@Simplicity the 'u' means unicode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.