5

I am using zbarimg to scan bar codes, I want to redirect the output to a python script. How can I redirect the output of the following command:

zbarimg code.png

to a python script, and what should be the script like?

I tried the following script:

#!/usr/local/bin/python
s = raw_input()
print s

I made it an executable by issuing the following:

chmod +x in.py

Than I ran the following :

zbarimg code.png | in.py

I know it's wrong but I can't figure out anything else!

Kartik Anand
  • 4,513
  • 5
  • 41
  • 72

3 Answers3

4

Use sys.stdin to read from stdin in your python script. For example:

import sys
data = sys.stdin.readlines()
dogbane
  • 266,786
  • 75
  • 396
  • 414
3

Using the pipe operator | from the command is correct, actually. Did it not work?

You might need to explicitly specify the path for the python script as in

zbarimg code.png | ./in.py

and as @dogbane says, reading from stdin like sys.stdin.readlines() is better than using raw_input

Leopd
  • 41,333
  • 31
  • 129
  • 167
2

I had to invoke the python program command as somecommand | python mypythonscript.py instead of somecommand | ./mypythonscript.py. This worked for me. The latter produced errors.

My purpose: Sum up the durations of all mp3 files by piping output of soxi -D *mp3 into python: soxi -D *mp3 | python sum_durations.py


Details:

soxi -D *mp3produces:

122.473016
139.533016
128.456009
307.802993
...

sum_durations.py script:

import sys
import math
data = sys.stdin.readlines()
#print(data)
sum = 0.0
for line in data:
    #print(line)
    sum += float(line)

mins = math.floor(sum / 60)
secs = math.floor(sum) % 60

print("total duration: " + str(mins) + ":" + str(secs))
zoza
  • 21
  • 1