2

I am quite a newbie to Linux. I have a very simple Python script that accepts command line arguments and prints them. Now I just want to pass the date command's output as input to this Python script and print it. The Python script looks like this.

import sys
print "command line arguments recieved are"
for i in range(0,len(sys.argv)) :
   print sys.argv[i]

While running this program in order to pass the date command's output to script I just did

date | python exmp.py

Is this the right way to pass one command's output as input of a program? My program is not taking input from date command. The output I am getting looks like this

command line arguments recieved are
exmp.py

I am really unable to find out what wrong thing am I doing. Please help me in resolving this.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Chiyaan Suraj
  • 1,021
  • 2
  • 13
  • 27

2 Answers2

1

If you want to pass the output of date to python you can pipe it (using |) or you can pass it as a command line argument.

Consider the following python program:

import sys

print "Command line input:"
print sys.argv;

print ""

print "Standard input:"
print sys.stdin.read()

You can call this program on the command line with:

echo "hmm, this is text" | python test3.py "`date`"

When I run the program I get:

Command line input:
['test3.py', 'Mon  9 Feb 21:10:00 AEST 2015']

Standard input:
hmm, this is text

The left quotes around date specify that date should be run and that you don't just mean the text date. The double quotes around date force the output of date to be a single command line argument passed to python. Experiment with removing the outer quotes, the inner quotes and both.

The command of the left of the | symbol is executed first, the result is then passed to the program on the right as standard input. Instead of echo you could use:

date | python test3.py

If you just want to get the date into python, take a look at some of the built in python modules.

ilent2
  • 5,171
  • 3
  • 21
  • 30
0

You are mixing up two different facilities of the Unix shell.

What you are asking can be done like

python exmp.py $(date)

or you could change your script to read standard input:

date | python -c 'import sys
for line in sys.stdin: print line'

The expression $(date) performs a command substitution: the command in the brackets is run, and its output is substituted for the bracket expression.

There is a tool called xargs for mixing the two:

date | xargs python exmp.py
tripleee
  • 175,061
  • 34
  • 275
  • 318