如何通过命令行参数解析IP:port列表至HOSTS变量供函数使用
解决命令行解析IP:port列表到HOSTS变量的问题
看你的代码,核心问题在于用type=list来解析--hosts参数是不对的——argparse的type=list会把输入的整个字符串拆成单个字符的列表,而不是你想要的分割后的IP:port列表。下面给你两种可行的解决方案:
方案1:解析逗号分隔的host字符串
自定义一个解析函数,把用户输入的逗号分隔字符串转换成host列表:
import argparse import requests ALLOWED_FUNCTIONS = ['check_head_block'] # 替换成你的实际允许函数列表 URLS = {'get_info': 'http://{host}/api/get_info'} # 替换成你的实际URL模板 # 自定义host解析函数:分割逗号,去除空格和空字符串 def parse_host_list(hosts_input): return [host.strip() for host in hosts_input.split(',') if host.strip()] parser = argparse.ArgumentParser(description='chain info checker') parser.add_argument('host', help='Single host address (if not using --hosts)') parser.add_argument('function', help='Check to run', choices=ALLOWED_FUNCTIONS) # 使用自定义类型解析--hosts参数 parser.add_argument('--hosts', dest='HOSTS', type=parse_host_list, help='Comma-separated list of hosts (e.g., 192.168.1.1:8080,10.0.0.1:9090)') args = parser.parse_args() # 如果提供了--hosts就用它,否则用单个positional host HOSTS = args.HOSTS or [args.host] def read_head_block_ints(): for host in HOSTS: try: request_url = URLS['get_info'].format(host=host) response = requests.get(request_url, timeout=10) response.raise_for_status() # 捕获HTTP错误状态码 data = response.json() # 根据实际响应格式调整,比如text/bytes # 这里添加你的业务逻辑:从data中提取head block ints print(f"Processed host {host}: Head block data retrieved successfully") except requests.exceptions.RequestException as e: print(f"Failed to access {host}: {str(e)}") # 根据命令行指定的函数执行 if args.function == 'check_head_block': read_head_block_ints()
使用方式:
# 单个host(用positional参数) python your_script.py 127.0.0.1:8000 check_head_block # 多个host(用--hosts) python your_script.py 127.0.0.1:8000 check_head_block --hosts 192.168.1.2:8000,10.0.0.3:8000
方案2:接受多个空格分隔的host参数
如果更喜欢让用户用空格分开多个host,可以用nargs='+',这样用户可以重复输入--hosts或者一次性输入多个:
# 修改--hosts参数的定义 parser.add_argument('--hosts', dest='HOSTS', nargs='+', help='Space-separated list of hosts (e.g., --hosts 192.168.1.1:8080 10.0.0.1:9090)')
使用方式:
python your_script.py 127.0.0.1:8000 check_head_block --hosts 192.168.1.2:8000 10.0.0.3:8000 # 或者重复--hosts python your_script.py 127.0.0.1:8000 check_head_block --hosts 192.168.1.2:8000 --hosts 10.0.0.3:8000
为什么原代码的type=list不生效?
argparse的type参数是把用户输入的单个字符串转换成指定类型。比如用户输入--hosts 1.1.1.1:80,2.2.2.2:80,type=list会把这个字符串拆成字符列表:['1', '.', '1', '.', '1', '.', '1', ':', '8', '0', ',', '2', '.', '2', '.', '2', '.', '2', ':', '8', '0'],完全不是你需要的host列表,所以必须用自定义解析或者nargs来处理。
内容的提问来源于stack exchange,提问作者Ankh2054
相关产品推荐
相关产品推荐

