0

I have this python script, I now open an image from a given path in the script itself, what I need is a dynamical way to pass the image to the script.

For example: python pixel.py 9tiff, I will be running this from php with shell exec and I will need to pass different images each time, so I can't hard code the image name in to a script itself

import os, sys
import Image

im = Image.open('/www/test/tiffFiles/9.tiff')
rgb_im = im.convert('RGB')
r0, g0, b0 = rgb_im.getpixel((20, 20))
r1, g1, b1 = rgb_im.getpixel((40, 40))
r2, g2, b2 = rgb_im.getpixel((60, 60))
print(r0, g0, b0)
print(r1, g1, b1)
print(r2, g2, b2)
Tomkis90
  • 31
  • 6
  • Possible duplicate of [How to read/process command line arguments?](https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments) – galmeriol May 30 '18 at 07:54
  • `Sys.argv`. Have a look here: https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments – ZiGaelle May 30 '18 at 07:54

2 Answers2

1

There are tons of similar questions out there, but if you want an easy solution, use sys.argv

import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)

But the best is always argparse

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
Luca
  • 105
  • 1
  • 1
  • 7
0

Parsing command line arguments in python are fairly simple. you can change the your script to as follows:

import sys
import Image

if __name__ =='__main__':
    im = Image.open(str(sys.argv[1]))
    rgb_im = im.convert('RGB')
    r0, g0, b0 = rgb_im.getpixel((20, 20))
    r1, g1, b1 = rgb_im.getpixel((40, 40))
    r2, g2, b2 = rgb_im.getpixel((60, 60))
    print(r0, g0, b0)
    print(r1, g1, b1)
    print(r2, g2, b2)

In Python argv[0] variable is always reserved for the name of the python script. python myScript.py 9tiff here argv[0] is held by myScript.py and argv[1] is used by 9tiff

Yayati Sule
  • 1,601
  • 13
  • 25