Search code examples
pythonbashuser-input

How can write python code to take input from user via bash script


I want to calculate some measures for different cities and for each city 5 times. I need to give data via a bash script.

 #!/bin/bash 
 cities=('paris''helsinki' 'rome') 
 for city in "${cities[@]}" do
         for (( i = 1; i <= 5; i++ ))
         do
                 srun python3 random_graph.py  "$city" > "$city"/"city"_"$i".json
         done

done

I wrote my python code like this:

 def get_network_measure(city):
        some code
 
 if __name__ == '__main__':
       city = input()
       result = get_network_measure(city)

but I need to give the city name at the same time, not giving in the second step by input() function. I need something like this when I run in bash

python mycode.py paris

Solution

  • You need to read from arguments passed to the interpreter. These are available in sys.argv.

    You also need to write to the standard output, sys.stdout. You can do this by default using print:

    import sys
    
    def main(argv):
        city = argv[1]
        print(get_network_measure(city))
    
    def get_network_measure(city):
        return 110
    
    
    if __name__ == '__main__':
        main(sys.argv)
    

    You could also pipe input in using sys.stdin.