Pass arguments from cmd to python script

后端 未结 3 1009
轮回少年
轮回少年 2021-01-02 18:31

I write my scripts in python and run them with cmd by typing in:

C:\\> python script.py

Some of my scripts contain separate algorithms a

3条回答
  •  遥遥无期
    2021-01-02 19:14

    Try using the getopt module. It can handle both short and long command line options and is implemented in a similar way in other languages (C, shell scripting, etc):

    import sys, getopt
    
    
    def main(argv):
    
        # default algorithm:
        algorithm = 1
    
        # parse command line options:
        try:
           opts, args = getopt.getopt(argv,"a:",["algorithm="])
        except getopt.GetoptError:
           
           sys.exit(2)
    
        for opt, arg in opts:
           if opt in ("-a", "--algorithm"):
              # use alternative algorithm:
              algorithm = arg
    
        print "Using algorithm: ", algorithm
    
        # Positional command line arguments (i.e. non optional ones) are
        # still available via 'args':
        print "Positional args: ", args
    
    if __name__ == "__main__":
       main(sys.argv[1:])
    

    You can then pass specify a different algorithm by using the -a or --algorithm= options:

    python  -a2               # use algorithm 2
    python  --algorithm=2    # ditto
    

    See: getopt documentation

提交回复
热议问题