Reputation: 48916
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.
Upvotes: 0
Views: 1263
Reputation: 4010
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.
Upvotes: 2
Reputation: 3485
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.
Upvotes: 1