Skip to content

Instantly share code, notes, and snippets.

@justjkk
Created May 4, 2012 13:34
Show Gist options
  • Save justjkk/2594831 to your computer and use it in GitHub Desktop.
Save justjkk/2594831 to your computer and use it in GitHub Desktop.
CLI Wrapper around python-phonenumbers library
#!/usr/bin/env python
"""Minimal CLI wrapper around phonenumbers library so that PHP can use it
Author: Kishore Kumar <justjkk@gmail.com>
Usage: python ph.py <command> <args>
Commands:
help - Print this
parse - Parse a phonenumber and returns number type and E164 formatted
phone number. Arguments: number(required), country(optional)
"""
from __future__ import print_function
import sys
from phonenumbers import parse as parse_number, format_number, number_type, \
is_valid_number, PhoneNumberFormat
def parse_command(number, country='IN'):
"""Parse Command
:param number - User inputted phonenumber that needs to be parsed
:param country - Default country. If is not provided or is empty,
'IN' is assumed
:raises ValueError if phone number cannot be parsed
:returns integer representing number type and E164 formatted phone number
Number Types:
0 - Landline
1 - Mobile
2 - Mobile or Landline
99 - Unknown (Note: Returned number is not E164 formatted in this case)
>>> parse_command('9876543210')
1 +919876543210
>>> parse_command('04425368416')
0 +914425368416
>>> parse_command('78036849474')
99 78036849474
>>> parse_command('alpha')
Traceback (most recent call last):
...
NumberParseException: (1) The string supplied did not seem to be a phone \
number.
>>> parse_command('020 8366 1177', 'GB')
0 +442083661177
>>> parse_command('9876543210', '')
1 +919876543210
"""
p = parse_number(number, country or 'IN')
if is_valid_number(p):
print(number_type(p), format_number(p, PhoneNumberFormat.E164))
else:
print(number_type(p), p.national_number)
if __name__ == "__main__":
if len(sys.argv) > 1:
command = sys.argv[1]
if command == 'parse':
if 2 < len(sys.argv) < 5:
parse_command(*sys.argv[2:])
else:
print('Incorrect number of arguments.\n'
'Type: %s help' % sys.argv[0])
sys.exit(1)
elif command == 'help':
print(__doc__)
sys.exit(0)
else:
print('Command not recognized.\n'
'Type: %s help' % sys.argv[0])
sys.exit(1)
else:
print(__doc__)
sys.exit(1)
<?php
$num = '98505 55424';
exec("./ph.py parse \"$num\" NP", $output);
$data = explode(' ', $output[0]);
echo "Number type: $data[0]\n";
echo "Number: $data[1]\n";
@hernamesbarbara
Copy link

Holy moly. I was just writing this exact script but did a quick google search to see if someone had already done it...boom! Beat me to it. Thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment