import argparse parser = argparse.ArgumentParser(description='Process MySQLMonitor command line arguments') parser.add_argument('-h', '--host', type=str, help='mysql host') parser.add_argument('-p', '--port', type=str, help='mysql port') parser.add_argument('--username', type=str, help='mysql username') parser.add_argument('--password', type=str, help='mysql password') parser.add_argument('--help', action='store_true', help='Help Info') args = parser.parse_args() helpinfo = '''[?]CommandLine: -h --host mysql host -p --port mysql port --username mysql username --password mysql password --help help info eg: python MySQLMonitor.py -h 127.0.0.1 --username CoolCat --password mysqlmonitor ''' if args.help: print(helpinfo) exit() if not (args.host and args.username and args.password): print(helpinfo) exit() dbhost = args.host dbport = args.port or '3306' dbuser = args.username dbpass = args.password print(dbhost,dbport,dbuser,dbpass)就是这串代码运行报错,怎么修改呢
时间: 2023-12-28 13:06:04 浏览: 91
http-parser.zip_compasscds_content-type_http-parser_http-parser
这段代码中定义了一个 --help 选项,但是 argparse 库已经默认提供了 -h 和 --help 选项,因此会冲突。解决方法是将自定义的 --help 选项改为其他名称,例如 --info。修改后的代码如下:
```
import argparse
parser = argparse.ArgumentParser(description='Process MySQLMonitor command line arguments')
parser.add_argument('-H', '--host', type=str, help='mysql host')
parser.add_argument('-p', '--port', type=str, help='mysql port')
parser.add_argument('--username', type=str, help='mysql username')
parser.add_argument('--password', type=str, help='mysql password')
parser.add_argument('--info', action='store_true', help='Help Info')
args = parser.parse_args()
helpinfo = '''[?]CommandLine:
-H --host mysql host
-p --port mysql port
--username mysql username
--password mysql password
--info help info
eg: python MySQLMonitor.py -H 127.0.0.1 --username CoolCat --password mysqlmonitor'''
if args.info:
print(helpinfo)
exit()
if not (args.host and args.username and args.password):
print(helpinfo)
exit()
dbhost = args.host
dbport = args.port or '3306'
dbuser = args.username
dbpass = args.password
print(dbhost,dbport,dbuser,dbpass)
```
修改后的代码将 --help 改为了 --info,同时将 -h 改为了 -H,避免冲突,可以正常运行了。
阅读全文