Python3.8中argparse接收命令行中文字符参数异常如何解决
解决方法
核心问题原因
你自定义的两个编码转换函数做了多余的编码操作,将原本的字符串类型转为了bytes类型,打印时就会输出带b前缀的十六进制字节序列,并不是argparse本身不支持中文参数。Python3环境下argparse默认会自动将命令行输入的参数解码为Unicode字符串,不需要额外做编码转换。
正确实现代码
import argparse import sys # 控制台输出编码设置(Windows环境按需添加) sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') class Parser(argparse.ArgumentParser): @staticmethod def optparse(): parser = argparse.ArgumentParser() mandatory = parser.add_argument_group("mandatory") mandatory.add_argument( "-k", "--keyword", dest="keywordToUse", default=None, help="Specify a keyword" ) mandatory.add_argument( "-f", "--keyword-file", dest="keywordFile", default=None, help="Specify a list of keywords (one per line) to run through" ) return parser.parse_args() if __name__ == "__main__": args = Parser.optparse() # 直接使用返回的参数即可,不需要额外编码转换 keyword = args.keywordToUse print(f"[10:12:28][I] starting search on a total of 1 unique keyword(s)") print(f"[10:12:28][D] currently processing keyword: '{keyword}'") print(f"[10:12:28][D] attempting search with keyword: '{keyword}'") print(f"[10:12:29][I] found a total of 0 result(s) using keyword: '{keyword}'") # 如果需要读取关键词文件,打开文件时指定utf-8编码即可 if args.keywordFile: with open(args.keywordFile, 'r', encoding='utf-8') as f: keyword_list = [line.strip() for line in f if line.strip()]
兼容Windows环境的额外操作
如果在Windows的cmd/powershell中运行仍然出现乱码,可以在执行脚本前先运行命令切换控制台编码为UTF-8:chcp 65001
内容的提问来源于stack exchange,提问作者user12969777
相关产品推荐
相关产品推荐

