在 Python 中使用 argparse 将命令行参数解析为 IP : 端口格式
Parse command line arguments into a IP : Port format using argparse in Python
我正在尝试使用 argparse 将 2 个命令行参数解析为我的脚本,格式如下 client.py [-n IP] [-p PORT]
到目前为止,我已经实现了以下内容:
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Gets IP and PORT from command line and parses them
ConnectionInfo = argparse.ArgumentParser()
ConnectionInfo.add_argument("-n", default=socket.gethostname())
ConnectionInfo.add_argument("-p", type=int, default='58000')
ConnectionInfoParsed = ConnectionInfo.parse_args()
# Saves the parsed IP and Port
HOST = ConnectionInfoParsed.n
PORT = ConnectionInfoParsed.p
# Connects to Server
connection.connect((HOST, PORT))
但是当我执行时:
py client.py [-n 127.0.0.1] [-p 58000]
我收到以下错误
usage: client.py [-h] [-n N] [-p P]
client.py: error: unrecognized arguments: [-n 127.0.0.1] [-p 58000]
任何人都可以帮助我解决这里的问题,以及错误中的 [-h]
参数来自哪里,因为我没有为它添加任何参数?
正如 hpaulj 提到的那样
I'd expect you to use py client.py -n 127.0.0.1 -p 58000. No brackets.
问题已解决
我正在尝试使用 argparse 将 2 个命令行参数解析为我的脚本,格式如下 client.py [-n IP] [-p PORT]
到目前为止,我已经实现了以下内容:
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Gets IP and PORT from command line and parses them
ConnectionInfo = argparse.ArgumentParser()
ConnectionInfo.add_argument("-n", default=socket.gethostname())
ConnectionInfo.add_argument("-p", type=int, default='58000')
ConnectionInfoParsed = ConnectionInfo.parse_args()
# Saves the parsed IP and Port
HOST = ConnectionInfoParsed.n
PORT = ConnectionInfoParsed.p
# Connects to Server
connection.connect((HOST, PORT))
但是当我执行时:
py client.py [-n 127.0.0.1] [-p 58000]
我收到以下错误
usage: client.py [-h] [-n N] [-p P]
client.py: error: unrecognized arguments: [-n 127.0.0.1] [-p 58000]
任何人都可以帮助我解决这里的问题,以及错误中的 [-h]
参数来自哪里,因为我没有为它添加任何参数?
正如 hpaulj 提到的那样
I'd expect you to use py client.py -n 127.0.0.1 -p 58000. No brackets.
问题已解决