-1

I'm trying to print today's date using os.sytem and commands.getoutput using python.

My code is :

    import os, commands
print os.system("date +%Y%m%d%T") print commands.getoutput("date +%Y%m%d%T")

=========Ouput :-=============

Case 1:

./test.py

First print statement's O/P: 2014071713:25:21 0
Second print statement's O/P:
2014071713:25:21

Case 2:
I tried trace using import pdb;pdb.set_trace()

    print os.system("date +%Y%m%d%T")
    (Pdb) n
    2014071713:25:21
    0
print commands.getoutput("date +%Y%m%d%T") (Pdb) n 2014071713:31:29 --Return--

Why first print statement appending 0 in both the cases and second print statement is not appending anything in case 1 but it is appending --Return-- in case 2 ?

I know there are some modules for date / time in python but I want know why it is appending those extra strings in output ?

Naive
  • 492
  • 3
  • 8
  • 20
  • Have you read their documentation? And `commands` module was deprecated a long time ago, don't use it. And don't use `os.system` either, use [subprocess](https://docs.python.org/2/library/subprocess.html#module-subprocess) module. – Ashwini Chaudhary Jul 17 '14 at 08:19
  • I know it is deprecated but I wanted to know reason for those O/P – Naive Jul 17 '14 at 09:10

1 Answers1

2

When you use os.system the return value is the called commands return code. The output of the called command is going straight to stdout

When you use commands.getoutput the called commands output is being captured, rather than going to stdout. The return code is not shown.

The easiest way to test the difference is to do:

a = os.system("some command")
b = commands.getoutput("some command")
print "commands have run"
print "output of os.system:",a
print "output of commands.getoutput",b

Note the commands module is depreciated. As noted in the comment above, you should look at using subprocess instead.

ebarr
  • 7,704
  • 1
  • 29
  • 40