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!
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With