Python命令行参数处理循环的代码块执行逻辑及缩进问题求助
解决命令行参数处理后代码重复执行的问题
看起来你遇到的核心问题是业务代码被错误缩进在了参数处理的for循环内部,导致每处理一个命令行选项(比如-i和-s),就会执行一次那段核心逻辑。咱们一步步来修正:
问题根源
你原本的代码里,那段标注了#if ip address is not defined qpid-route will not work的代码块,缩进位置不对——它被包含在了for opt, arg in opts:循环里面,所以每次循环处理一个参数后,都会跑一遍这段代码。这就是为什么你处理完-i会执行一次,处理完-s又执行一次的原因。用break或continue只会打乱参数处理流程,没法解决根本问题。
修正方案
把核心业务代码块的缩进调整到for循环结束之后,等所有命令行参数都处理完毕,再统一执行一次逻辑。另外我还帮你修复了几个小细节:
- 把
file()换成更规范的open()(两者在Python2里都能用,但open()是推荐写法) - 修复了最后
main(sys.argv[1:])的缩进错误(它原本缩进了,应该和if __name__ == "__main__":对齐) - 调整了跳过文件行的逻辑(原来的
range(3)只会跳过3行,注释说要跳过4行,改成range(4)更准确) - 改用
with语句处理文件,自动关闭文件更安全
修正后的完整代码
import re import os import sys import getopt import pdb ipaddress = "" scac = '' def main(argv): ipaddress = "" scac = '' pdb.set_trace() try: opts, args = getopt.getopt(argv,"hi:s:",["ipaddress=","scac="]) if not opts: # if no option given print 'usage test.py -i <ipaddress> -s <scac>' sys.exit(2) except getopt.GetoptError: print 'test.py -i <ipaddress> -s <scac>' sys.exit(2) # 先处理所有命令行参数 for opt, arg in opts: if opt == '-h': print 'FedConnectStatus.py -i <iobipaddress> -s <scac>' sys.exit() elif opt in ("-i", "--ipaddress"): ipaddress = arg elif opt in ("-s", "--scac"): scac = arg # 所有参数处理完成后,再执行核心逻辑(这里缩进正确了!) # if ip address is not defined qpid-route will not work if not ipaddress: print 'ip address needed' else: print(os.getcwd()) # If no scac is given grab every federated connection and report if not scac: # open file to read with open('qpid.txt', 'r') as f: nameList = [] statusList = [] # skip first 4 lines for i in range(4): next(f) # iterate over the lines in the file for line in f: # split the line into a list of column values columns = line.split(None, 5) # clean any whitespace off the items columns = [col.strip() for col in columns] # ensure the column has at least one value before processing if columns: nameList.append(columns[0]) statusList.append(columns[4]) print nameList print statusList if __name__ == "__main__": main(sys.argv[1:])
额外说明
- 现在参数处理循环会先把所有
-i和-s的参数都处理完,才会进入核心逻辑块,只会执行一次,不会重复运行了。 - 如果你用的是Python3,记得把
print语句改成print()函数(比如print('ip address needed'))。
内容的提问来源于stack exchange,提问作者jeff
相关产品推荐
相关产品推荐

