I'm trying to do the following: The script takes a line from the file, splits it, and then the phone number should be set as a variable for the asterisk dialplan.
File line looks like:
Doe,John,Adam,123456789
But I get an error:
Error converting phone_number to integer: invalid literal for int() with base 10: ''
At the same time, as I understand it, the variable is set, because if I print it, it exists.
phone: 123456789
Tell me, please, what is the error?
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}")
Update1:
If I remove the conversion to integer, I get this error:
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
Updated code
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}")
Update2 Code:
# 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()}")
Error:
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
As I can see from your error message, that empty string is passed to your int() function.
Check your file and your code again.
is being evaluated as True (May be due Python version).
Try to use ,