简体   繁体   中英

how to create a command-line-argument in python

How to create an argument in Python ? Assume I have a script install.py that executes packages on a host. I have another config script named config.py where i store the host name & package names. but I want to create my host name as an "argument" that i can run in terminal using this command install . And it should catch the host name as an argument. [ie 'install linuxServer1' and it should install directly to that host.]

#codes from config.py
hostName = "linuxServer1"

package=['test1',
         'test2'
        ]


#codes from install.py

Install = []

for i in config.package:
 Install.append("deploy:"+i+",host=")

for f in Install:
 subprocess.call(["fabric", f+config.hostName])

I think you should have a look on " argparse " module of python, it will solve your current problem :)

Lets take 1 example -

The following code is a Python program that takes a list of integers and produces either the sum or the max:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

If asked for help(Assuming the Python code above is saved into a file called prog.py)-

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

If invalid arguments are passed in, it will issue an error:

$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

sys.argv holds all of the command line arguments given to the python command.

import sys

if __name__ == "__main__":
    print(sys.argv) # the list containing all of the command line arguments
    if len(sys.argv) > 1: # The first item is the filename
        host = sys.argv[1]
        print(host)
import argparse
Install = []
hostName = str(sys.argv[1])

for i in config.package:
 Install.append("deploy:"+i+",host=")

for f in Install:
 subprocess.call(["fabric", f+hostName])

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