Python脚本设置Asterisk变量时的空值转整数错误排查
Python脚本读取文件设置Asterisk变量报错排查
我正在编写Python脚本,读取文件中的行并拆分,将手机号设置为Asterisk拨号计划的变量。文件行格式如下:
Doe,John,Adam,123456789
运行时出现错误:
Error converting phone_number to integer: invalid literal for int() with base 10: ''
虽然打印变量能显示正确手机号(如phone: 123456789),但报错仍存在。移除整数转换操作后,仍出现类似错误,以下是多版代码及对应报错信息,请求排查问题根源。
初始代码及报错
with open(file_path, 'r') as file: i = 0 for line in file: parts = line.strip().split(',') # Ensure that there are enough parts in the line if len(parts) >= 4: surname, name, lastname, phone_number = parts[:4] # Check if phone_number is not empty before conversion if phone_number.strip(): # Check if the stripped value is not empty try: phone_number = int(phone_number) agi.set_variable('PHONE_NUMBER', f"{phone_number}") except ValueError as e: print(f"Error converting phone_number to integer: {e}") except Exception as e: print(f"Error setting PHONE_NUMBER: {e}") else: print(f"Empty phone_number encountered on line {i + 1}, skipping...") else: print(f"Invalid line format on line {i + 1}: {line.strip()}") print(f"phone: {phone_number}")
报错信息:
Error converting phone_number to integer: invalid literal for int() with base 10: ''
Update1:移除整数转换后的代码及报错
更新后代码:
with open(file_path, 'r') as file: for line in file: parts = line.strip().split(',') # Ensure that there are enough parts in the line if len(parts) >= 4: surname, name, lastname, phone_number = parts[:4] # Check if phone_number is not empty before conversion if phone_number.strip(): # Check if the stripped value is not empty try: agi.set_variable('PHONE_NUMBER', phone_number.strip()) except Exception as e: print(f"Error setting PHONE_NUMBER: {e}") else: print(f"Empty phone_number encountered on line {i + 1}, skipping...") else: print(f"Invalid line format on line {i + 1}: {line.strip()}") print(f"name: {phone_number}")
报错信息:
COMMAND: SET VARIABLE "PHONE_NUMBER" "123456789" SET VARIABLE "PHONE_NUMBER" "123456789" RESULT_LINE: Error setting PHONE_NUMBER: invalid literal for int() with base 10: '' phone: 123456789
Update2:修改空值判断后的代码及报错
对应代码片段:
# Check if phone_number is not empty before conversion if len(phone_number) > 0: # Check if the stripped value is not empty try: agi.set_variable('PHONE_NUMBER', phone_number.strip()) except Exception as e: print(f"Error setting PHONE_NUMBER: {e}") else: print(f"Empty phone_number encountered on line {i + 1}, skipping...") else: print(f"Invalid line format on line {i + 1}: {line.strip()}")
报错信息:
COMMAND: SET VARIABLE "PHONE_NUMBER" "123456789" SET VARIABLE "PHONE_NUMBER" "123456789" RESULT_LINE: Error setting PHONE_NUMBER: invalid literal for int() with base 10: '' name: 123456789
内容的提问来源于stack exchange,提问作者Norbert Yuhas
相关产品推荐
相关产品推荐

