Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to python from bash script

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!

like image 281
CoXier Avatar asked Sep 22 '17 11:09

CoXier


People also ask

How do you pass arguments to a Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.


2 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).

like image 50
Ardit Avatar answered Sep 28 '22 16:09

Ardit


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.)

like image 31
chepner Avatar answered Sep 28 '22 15:09

chepner