Pass arguments to python from bash script

Viewed 12144

I have been working on a script mixture of bash and python script. The bash script can receive unknown count input arguments. For example :

tinify.sh  test1.jpg test2.jpg test3.jpg .....

After the bash receives all, it pass these arguments to tinify.py. Now I have come out two ways to do that.

  • Loop in bash and call python tinify.py testx.jpg

    In another word, python tinify test1.jpg then python tinify test2.jpg, finaly python tinify test3.jpg

  • Pass all arguments to tinify.py then loop in python

But there is a problem, I want to filter same parameter for example if user input tinify.sh test1.jpg test1.jpg test1.jpg , I only want tinify.sh test1.jpg.So I think it's easier to do in second way because python may be convenient.

How can I do to pass all arguments to python script? Thanks in advance!

4 Answers

In addition to Chepner's answer above:

#!/bin/bash
tinify.py "$@"

within python script, tinify.py:

from sys import argv
inputArgs = sys.argv[1:]
def remove_duplicates(l):
    return list(set(l))
arguments=remove_duplicates(inputArgs)

The list arguments will contain the arguments passed to python script (duplicated removed as set can't contain duplicated values in python).

You use $@ in tinify.sh

#!/bin/bash
tinify.py "$@"

It will be far easier to eliminate duplicates inside the Python script that to filter them out from the shell. (Of course, this raises the question whether you need a shell script at all.)

A python program can accept any number of command line arguments, using sys.argv — just remember that sys.argv[0] is the name of the script and actual arguments are contained in sys.argv[1:]

$ cat test_args.py
from sys import argv

prog_name = argv[0]
print('Program name:', prog_name)

for arg in argv[1:]:
    print(arg)
$ python test_args.py a b 'c d'
Program name: test_args.py
a
b
c d
$

note that an argument containing spaces must be quoted according to the shell syntax.

Your file tinify.py should start with the following (if you have two arguments):

import sys

arg1, arg2 = sys.argv[1], sys.argv[2]

sys.argv[0] is the name of the script itself. You can of course loop over sys.argv. Personally, i like to pass all the arguments as json objects, so afterwards I do json.loads()

Related