简体   繁体   中英

How can I automate a python program that requires two inputs in a linux command line?

I have a python program that I have parsed into the linux command line. It requires two inputs. The first input will always be the same and I want the second input to be anywhere from 1-1030.Is there a way I can get python to run that automatically in the command line and each time increase the second input by +1? I would like to do this so I do not have to manually type the second input 1030 times.

My command line looks something like this:

$ python ex_script.py -d (first input) -r (second input)

There are multiple possibilities to get inputs from the command line

  1. using import sys and sys.argv[n] will give you the n-th command line input as a string.
  2. using a library such as argparse

To avoid the second argument a very simple fix would be to write a counter into a file and make your program read the number in this file increase it by one override the file. You could also check in your program that the number is smaller than 1030.

I would write a short second script that runs the first script with the required arguments. Not sure if this is the best way, but it would be my first choice to use subprocess :

import subprocess

for i in range(1030):
    subprocess.run(['python', 'ex_script', 'arg1', str(i)])

Note that subprocess is specified with values in a list []. These values work in my Win10 environment, but you can adapt them for your own environment.

Just use for loops in bash.

for i in {1..1030}
do
    python ex_script.py -d <the first input here> -r $i
done

The loop will iterate through the numbers 1 to 1030. Then, you could put any command-line instructions inside the loop and use the variable $i, passing it as an argument for the instruction.

You could put it into a .sh file and make it executable using chmod +x .

Then run it as an executable script from the terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM