python command line parsing

When writing Python code, you need to pass in some parameters, which can be specified flexibly, rather than hard-coded in the code.

for example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '--flag_int',
    type=float,
    default=0.01,
    help='flag_int.'
)
FLAGS, unparsed = parser.parse_known_args()
print(FLAGS)
print(unparsed)
Command window input: $ python prog.py --flag_int 0.02 --double 0.03 a 1
The results are as follows:
 Namespace(flag_int=0.02)
['--double', '0.03', 'a', '1']

=============Analysis code==================================== ====

In python, command line parsing works well,

1. First import the command line parsing module

import argparse
import sys

2. Then create the object

parse=argparse.ArgumentParser()

3. Then add the command line

parse.add_argument("--learning_rate",type=float,default=0.01,help="initial learining rate")

For the function add_argumen(), the first is the parameter alias, the alias and the corresponding value should be entered at the terminal. The second is the data type, and the third is the default value. When you do not enter the value of the parameter in the terminal, the default value will be used. The fourth is the description of the help command to help you understand the role of the parameters.

There are some other optional parameters, like this program will output something when --verbosityis modified, and nothing if it is not modified.

A new parameter is added to the program actionand it takes the value store_true. That is, if the option --verboseis modified, then we assign it the value True, and if it has not been modified, then it is False. When you modify this value, in fact, whatever you specify, it will be assigned to True.

4.parse_known_args() is very useful. It is much like parse_args().

Let's talk about calling the parse_args() method for parsing first; it can be used after the parsing is successful.

for example:

def parse_args():

    parser = argparse.ArgumentParser() 

     help = The addresses to connect. parser.add_argument('addresses',nargs = '*',help = help)

     help = The filename to operate on.Default is poetry/ecstasy.txt parser.add_argument('filename',help=help) 

     args = parser.parse_args(); 

     return args

 if __name__ == '__main__':

     args = parse_args()

      print 'The filename is : %s .' % args.filename

     print 'The port is : %d.' % args.port

======================================但是

args = parser.parse_args()换成 FLAGS, unparsed = parser.parse_known_args()

print(FLAGS) 

print(unparsed)

命令窗口输入:$ python prog.py --flag_int 0.02 --double 0.03 a 1运行结果如下:

Namespace(flag_int=0.02)

['--double', '0.03', 'a', '1']parser.parse_known_args()

它在接受到多余的命令行参数时不报错。相反的,返回一个tuple类型的命名空间保存在FLAGS和一个保存着余下的命令行字符的list在unparsed。

====================下面给个完整一点的代码作为参考

import argparse
import os
FLAGS=None
def main():
    if tf.gfile.Exists(FLAGS.log_dir):
        tf.gfile.Delete_Recursively(FLAGS.log_dir)
    tf.gfile.MakeDirs(FLAGS.log_dir)
    
if __name__=='__main__':
    parser=argparse.ArgumentParser()
   
    parser.add_argument('--log_dir',type=str,default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),'tensorflow/mnist/logs/fully_connected_feed'),help='Directory to put the log data.')
    parser.add_argument('--fake_data',default=False,help='If true, uses fake data for unit testing.',action='store_true')
    
    FLAGS,unparsed=parser.parse_know_args()
    tf.app.run(main=main,argv=[sys.argv[0]]+unparsed)

argc 是 argument count的缩写,表示传入main函数的参数个数;

argv 是 argument vector的缩写,表示传入main函数的参数序列或指针,并且第一个参数argv[0]一定是程序的名称,并且包含了程序所在的完整路径,所以确切的说需要我们输入的main函数的参数个数应该是argc-1个;我们有时候这样写:

用arg=parse.parse_args(sys.argv[1:]),sys.argv[1:]来获取真正的第一个参数值.


总结:

使用步骤:

1:import argparse

2:parser = argparse.ArgumentParser()

3:parser.add_argument()

4:parser.parse_args() or  FLAGS,unparsed=parser.parse_know_args()



参考:

https://www.jianshu.com/p/e8010e85aeb3

https://blog.csdn.net/mameng1/article/details/54409910

https://www.cnblogs.com/xlqtlhx/p/8243592.html

https://www.2cto.com/kf/201412/363654.html

https://blog.csdn.net/dcrmg/article/details/51987413

https://www.cnblogs.com/zknublx/p/6106343.html

https://www.cnblogs.com/lovemyspring/p/3214598.html


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325876839&siteId=291194637