Run command line commands in python script

I have a program that runs from the command line, such as

python program.py 100 rfile

How can I write a new script so that instead of running it with just the argument “100”, I can run it sequentially with a list of arguments like [50, 100, 150, 200]?

Edit: the reason I'm asking is because I want to write down how "program.py" is executed with different arguments.

+3
source share
4 answers

If you create a bash file like this

#!/bin/bash
for i in 1 2 3 4 5
do
  python program.py $i rfile
done

then do chmod +xin this file, when you run it, it will run them sequentially:

python program.py 1 rfile
python program.py 2 rfile
python program.py 3 rfile
python program.py 4 rfile
python program.py 5 rfile
+7
source

Devrim script:

script :

import sys
do_something(sys.argv[1], sys.argv[2])

, :

def main(args):
    for arg in args[:-1]:
        do_something(arg, args[-1])

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

:

python program.py 50 100 150 200 rfile

, . , .

+6

Optparse

: python yourcode.py --input input.txt --output output.txt

, .

, - :

parser.add_option("-i","--input", action="store", type="int", nargs=4, dest="mylist")

python program.py -i 50 100 150 200

mylist .

+4

python script, , argparse ( ):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('rfile', type=argparse.FileType('r'))
parser.add_argument('numbers', nargs='+', type=int)
ns = parser.parse_args()

main Jon-Eric.

script

python the_script.py filename 1 2 3 4 5 6

ns.file, filename, , ns.numbers [1, 2, 3, 4, 5, 6].

argparse script , --help. , , docs.

argparse Python 2.7; , . easy_install argparse - , script .

+2

Source: https://habr.com/ru/post/1769672/


All Articles