prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message<|fim▁hole|><|fim▁end|> |
def show_help():
pass |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
<|fim_middle|>
__match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | '''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str<|fim_middle|>
__split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | _utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pat<|fim_middle|>
__print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | tern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if num<|fim_middle|>
f exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ber:
return str(line) + ':' + text.strip()
else:
return text.strip()
de |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
<|fim_middle|>
show_help():
pass<|fim▁end|> | filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim_middle|>
<|fim▁end|> | |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = <|fim_middle|>
lif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | text_file.read_file(target)
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = <|fim_middle|>
lse:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | target
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = <|fim_middle|>
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | None
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return <|fim_middle|>
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | None
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_t <|fim_middle|>
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ext = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result <|fim_middle|>
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | .append(line_text)
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return <|fim_middle|>
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | False
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return <|fim_middle|>
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patter <|fim_middle|>
lif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ns = pattern
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patter <|fim_middle|>
lse:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ns = [pattern]
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patter <|fim_middle|>
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ns = [str(pattern)]
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model <|fim_middle|>
odel = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | = 's'
m |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if mat <|fim_middle|>
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ch_pattern in line_text:
return True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return <|fim_middle|>
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, <|fim_middle|>
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return <|fim_middle|>
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if reg <|fim_middle|>
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ex_utils.check_line(match_pattern, line_text):
return True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return <|fim_middle|>
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if typ <|fim_middle|>
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | e(pattern) == types.FunctionType:
if pattern(line_text):
return True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pat <|fim_middle|>
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | tern(line_text):
return True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return <|fim_middle|>
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region <|fim_middle|>
eturn 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
r |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = <|fim_middle|>
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | int(region[0].strip())
_max = int(region[1].strip())
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return <|fim_middle|>
lse:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | str(line) + ':' + text.strip()
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return <|fim_middle|>
f exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | text.strip()
de |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, <|fim_middle|>
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_h <|fim_middle|>
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | elp()
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filena <|fim_middle|>
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | me = value
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
patter <|fim_middle|>
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | n = value
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number <|fim_middle|>
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | = True
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model <|fim_middle|>
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | = value
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print <|fim_middle|>
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | 'error : could not find file : ' + filename
sys.exit()
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print <|fim_middle|>
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | 'error : pattern is empty'
sys.exit()
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for li <|fim_middle|>
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | ne in result:
print line
|
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_h <|fim_middle|>
xcept GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | elp()
e |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def <|fim_middle|>(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | grep |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __matc<|fim_middle|>num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | h(line_ |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __spli<|fim_middle|>rn):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | t_region(patte |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __prin<|fim_middle|> text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | t(line, |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_c<|fim_middle|>:
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_help():
pass<|fim▁end|> | md(argv) |
<|file_name|>grep.py<|end_file_name|><|fim▁begin|># coding=utf-8
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pattern: regex pattern or line number pattern or reduce function: bool=action(str)
@param number: with line number
@param model: s: substring model, e: regex model, n: line number model, a: action model
@summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female']
print grep.grep(list, '^(?!.*female).*$', ':', [1])
output: ['huiyugeng', 'zhuzhu']
'''
if isinstance(target, basestring):
text = text_file.read_file(target)
elif isinstance(target, list):
text = target
else:
text = None
if not text:
return None
line_num = 1;
result = []
for line_text in text:
line_text = str(line_text)
if __match(line_num, line_text, model, pattern):
line_text = __print(line_num, line_text, number)
if line_text != None:
result.append(line_text)
line_num = line_num + 1
return result
def __match(line_num, line_text, model, pattern):
if str_utils.is_blank(line_text):
return False
if str_utils.is_blank(pattern):
return True
patterns = []
if type(pattern) == types.ListType:
patterns = pattern
elif type(pattern) == types.FunctionType:
patterns = [pattern]
else:
patterns = [str(pattern)]
if str_utils.is_empty(model) :
model = 's'
model = model.lower()
for match_pattern in patterns:
if model == 's':
if match_pattern in line_text:
return True
elif model == 'n':
_min, _max = __split_region(match_pattern)
if line_num >= _min and line_num <= _max:
return True
elif model == 'e':
if regex_utils.check_line(match_pattern, line_text):
return True
elif model == 'a':
if type(pattern) == types.FunctionType:
if pattern(line_text):
return True
return False
def __split_region(pattern):
if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern:
region = pattern[1: len(pattern) - 1].split(',')
if region != None and len(region) == 2:
_min = int(region[0].strip())
_max = int(region[1].strip())
return _min, _max
return 0, 0
def __print(line, text, number):
if number:
return str(line) + ':' + text.strip()
else:
return text.strip()
def exec_cmd(argv):
try:
filename = None
pattern = None
number = False
model = 'e'
if len(argv) > 2:
opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model'])
for name, value in opts:
if name in ('-h', '--help'):
show_help()
if name in ('-f', '--file'):
filename = value
if name in ('-p', '--pattern'):
pattern = value
if name in ('-n', '--number'):
number = True
if name in ('-m', '--model'):
model = value
if str_utils.is_empty(filename) or not os.path.exists(filename):
print 'error : could not find file : ' + filename
sys.exit()
if str_utils.is_empty(pattern):
print 'error : pattern is empty'
sys.exit()
result = grep(filename, pattern, number, model)
if result and isinstance(result, list):
for line in result:
print line
else:
show_help()
except GetoptError, e:
print 'error : ' + e.msg
except Exception, e:
print 'error : ' + e.message
def show_h<|fim_middle|> pass<|fim▁end|> | elp():
|
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
<|fim▁hole|> self.data = MockData()
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main()<|fim▁end|> | def setUp(self):
|
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
<|fim_middle|>
<|fim▁end|> | def setUp(self):
self.data = MockData()
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main() |
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
<|fim_middle|>
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main()<|fim▁end|> | self.data = MockData() |
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
self.data = MockData()
def test_random_data(self):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()<|fim▁end|> | data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!") |
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
self.data = MockData()
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def <|fim_middle|>(self):
self.data = MockData()
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main()<|fim▁end|> | setUp |
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
self.data = MockData()
def <|fim_middle|>(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main()<|fim▁end|> | test_random_data |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err<|fim▁hole|> hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok<|fim▁end|> |
coordinator = DataUpdateCoordinator( |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
<|fim_middle|>
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | """Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
<|fim_middle|>
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | """Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
<|fim_middle|>
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | """Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
<|fim_middle|>
<|fim▁end|> | """Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
<|fim_middle|>
return unload_ok
<|fim▁end|> | hass.data[DOMAIN].pop(entry.entry_id) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | async_setup_entry |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def <|fim_middle|>() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | async_get_pickup_events |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | async_reload_entry |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER
DEFAULT_NAME = "recollect_waste"
DEFAULT_UPDATE_INTERVAL = timedelta(days=1)
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up RainMachine as config entry."""
session = aiohttp_client.async_get_clientsession(hass)
client = Client(
entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
except RecollectError as err:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_get_pickup_events,
)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id)
async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
<|fim▁end|> | async_unload_entry |
<|file_name|>test.py<|end_file_name|><|fim▁begin|><|fim▁hole|>ghcnpy.intro()
# Print Latest Version
ghcnpy.get_ghcnd_version()
# Testing Search Capabilities
print("\nTESTING SEARCH CAPABILITIES")
ghcnpy.find_station("Asheville")
# Testing Search Capabilities
print("\nTESTING PULL CAPABILITIES")
outfile=ghcnpy.get_data_station("USW00003812")
print(outfile," has been downloaded")<|fim▁end|> | import ghcnpy
# Provide introduction |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig<|fim▁hole|>
class CirculoConfig(AppConfig):
name = 'circulo'<|fim▁end|> | |
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
class CirculoConfig(AppConfig):
<|fim_middle|>
<|fim▁end|> | name = 'circulo' |
<|file_name|>doc_view_list.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*-
SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;"""
FOUND_ROWS = True
ROOT = "doc_view_list"
ROOT_PREFIX = "<doc_view_edit />"
ROOT_POSTFIX= None
XSL_TEMPLATE = "data/af-web.xsl"
EVENT = None
WHERE = ()<|fim▁hole|>PARAM = None
TITLE="Список видов документов"
MESSAGE="ошибка получения списка видов документов"
ORDER = None<|fim▁end|> | |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>from importlib import import_module
from inspect import getdoc
def attribs(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B', <|fim▁hole|> print(d)<|fim▁end|> | '/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a) |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>from importlib import import_module
from inspect import getdoc
def attribs(name):
<|fim_middle|>
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d)<|fim▁end|> | mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod) |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>from importlib import import_module
from inspect import getdoc
def attribs(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
<|fim_middle|>
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d)<|fim▁end|> | pass |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>from importlib import import_module
from inspect import getdoc
def attribs(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
<|fim_middle|>
<|fim▁end|> | attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d) |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>from importlib import import_module
from inspect import getdoc
def <|fim_middle|>(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d)<|fim▁end|> | attribs |
<|file_name|>xorg_driver.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | ../../../../share/pyshared/jockey/xorg_driver.py |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):<|fim▁hole|> query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)<|fim▁end|> | |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
<|fim_middle|>
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return "" |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
<|fim_middle|>
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
<|fim_middle|>
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | """
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return "" |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
<|fim_middle|>
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | degraded_netgen = 3 |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
<|fim_middle|>
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | degraded_netgen = 2 |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
<|fim_middle|>
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
<|fim_middle|>
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | ser.close() |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
<|fim_middle|>
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
<|fim_middle|>
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | ip = "no ip" |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
<|fim_middle|>
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
<|fim_middle|>
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
<|fim_middle|>
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | response['color'] = i3s_config['color_degraded'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
<|fim_middle|>
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | response['color'] = i3s_config['color_good'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
<|fim_middle|>
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem") |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
<|fim_middle|>
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | pass |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
<|fim_middle|>
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
<|fim_middle|>
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
<|fim_middle|>
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | return addresses[ni.AF_INET][0]['addr'] |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1) |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def <|fim_middle|>(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | wwan_status |
<|file_name|>wwan_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There should be no need to configure this, but
feel free to experiment.
Default is 115200.
- cache_timeout : How often we refresh this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
useful if you want to keep track of where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
Default is 'WWAN: {error}'
- format_no_service : What to display when the modem does not have a
network connection. This allows to omit the then
meaningless network generation. Therefore the
default is 'WWAN: ({status}) {ip}'
- format_up : What to display upon regular connection
Default is 'WWAN: ({status}/{netgen}) {ip}'
- interface : The default interface to obtain the IP address
from. For wvdial this is most likely ppp0.
For netctl it can be different.
Default is: ppp0
- modem : The device to send commands to. Default is
- modem_timeout : The timespan betwenn querying the modem and
collecting the response.
Default is 0.4 (which should be sufficient)
@author Timo Kohorst [email protected]
PGP: B383 6AE6 6B46 5C45 E594 96AB 89D2 209D DBF3 2BB5
"""
import subprocess
import netifaces as ni
import os
import stat
import serial
from time import time, sleep
class Py3status:
baudrate = 115200
cache_timeout = 5
consider_3G_degraded = False
format_down = 'WWAN: down'
format_error = 'WWAN: {error}'
format_no_service = 'WWAN: {status} {ip}'
format_up = 'WWAN: {status} ({netgen}) {ip}'
interface = "ppp0"
modem = "/dev/ttyUSB1"
modem_timeout = 0.4
def wwan_status(self, i3s_output_list, i3s_config):
query = "AT^SYSINFOEX"
target_line = "^SYSINFOEX"
# Set up the highest network generation to display as degraded
if self.consider_3G_degraded:
degraded_netgen = 3
else:
degraded_netgen = 2
response = {}
response['cached_until'] = time() + self.cache_timeout
# Check if path exists and is a character device
if os.path.exists(self.modem) and stat.S_ISCHR(os.stat(
self.modem).st_mode):
print("Found modem " + self.modem)
try:
ser = serial.Serial(
port=self.modem,
baudrate=self.baudrate,
# Values below work for my modem. Not sure if
# they neccessarily work for all modems
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
if ser.isOpen():
ser.close()
ser.open()
ser.write((query + "\r").encode())
print("Issued query to " + self.modem)
sleep(self.modem_timeout)
n = ser.inWaiting()
modem_response = ser.read(n)
ser.close()
except:
# This will happen...
# 1) in the short timespan between the creation of the device node
# and udev changing the permissions. If this message persists,
# double check if you are using the proper device file
# 2) if/when you unplug the device
PermissionError
print("Permission error")
response['full_text'] = self.format_error.format(
error="no access to " + self.modem)
response['color'] = i3s_config['color_bad']
return response
# Dissect response
for line in modem_response.decode("utf-8").split('\n'):
print(line)
if line.startswith(target_line):
# Determine IP once the modem responds
ip = self._get_ip(self.interface)
if not ip:
ip = "no ip"
modem_answer = line.split(',')
netgen = len(modem_answer[-2]) + 1
netmode = modem_answer[-1].rstrip()[1:-1]
if netmode == "NO SERVICE":
response['full_text'] = self.format_no_service.format(
status=netmode,
ip=ip)
response['color'] = i3s_config['color_bad']
else:
response['full_text'] = self.format_up.format(
status=netmode,
netgen=str(netgen) + "G",
ip=ip)
if netgen <= degraded_netgen:
response['color'] = i3s_config['color_degraded']
else:
response['color'] = i3s_config['color_good']
elif line.startswith("COMMAND NOT SUPPORT") or line.startswith(
"ERROR"):
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_error.format(
error="unsupported modem")
else:
# Outputs can be multiline, so just try the next one
pass
else:
print(self.modem + " not found")
response['color'] = i3s_config['color_bad']
response['full_text'] = self.format_down
return response
def <|fim_middle|>(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]['addr']
return ""
if __name__ == "__main__":
from time import sleep
x = Py3status()
config = {
'color_good': '#00FF00',
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
}
while True:
print(x.wwan_status([], config))
sleep(1)
<|fim▁end|> | _get_ip |
<|file_name|>config.py<|end_file_name|><|fim▁begin|>import os
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = "super_secret_key"
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']<|fim▁hole|> DEBUG = True
class TestingConfig(Config):
TESTING = True<|fim▁end|> |
class DevelopmentConfig(Config):
DEVELOPMENT = True |
<|file_name|>config.py<|end_file_name|><|fim▁begin|>import os
class Config(object):
<|fim_middle|>
class ProductionConfig(Config):
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
<|fim▁end|> | DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = "super_secret_key"
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] |
<|file_name|>config.py<|end_file_name|><|fim▁begin|>import os
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = "super_secret_key"
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
<|fim_middle|>
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
<|fim▁end|> | DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.