本文整理汇总了Python中fileinput.filename方法的典型用法代码示例。如果您正苦于以下问题:Python fileinput.filename方法的具体用法?Python fileinput.filename怎么用?Python fileinput.filename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fileinput
的用法示例。
在下文中一共展示了fileinput.filename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def __call__(self, files=None):
manager = CommandManager()
try:
for line in fileinput.input(files=files):
if line[0] == '#':
continue
action = shlex.split(line.rstrip())
if len(action) < 1:
continue
cmd = manager.get(action[0])
args = action[1:]
result = cmd.parse_and_call(*args)
if result:
printo(result)
except IOError:
raise CommandError("Cannot read from file: {}".format(fileinput.filename()))
except CommandNotFound:
raise CommandError("Command {} not found".format(action[0]))
finally:
fileinput.close()
示例2: test_zero_byte_files
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def test_zero_byte_files(self):
t1 = t2 = t3 = t4 = None
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
t3 = writeTmp(3, ["The only line there is.\n"])
t4 = writeTmp(4, [""])
fi = FileInput(files=(t1, t2, t3, t4))
line = fi.readline()
self.assertEqual(line, 'The only line there is.\n')
self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 1)
self.assertEqual(fi.filename(), t3)
line = fi.readline()
self.assertFalse(line)
self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 0)
self.assertEqual(fi.filename(), t4)
fi.close()
finally:
remove_tempfiles(t1, t2, t3, t4)
示例3: more
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def more(filenames, pagesize=10, clear=False, fmt='{line}'):
'''Display content of filenames pagesize lines at a time (cleared if specified) with format fmt for each output line'''
fileinput.close() # in case still open
try:
pageno = 1
if clear:
clear_screen()
for line in fileinput.input(filenames, openhook=fileinput.hook_encoded("utf-8")):
lineno, filename, filelineno = fileinput.lineno(), fileinput.filename(), fileinput.filelineno()
print(fmt.format(**locals()), end='')
if pagesize and lineno % pagesize == 0:
console.alert('Abort or continue', filename, 'Next page') # TODO: use less intrusive mechanism than alert
pageno += 1
if clear:
clear_screen()
finally:
fileinput.close()
# --- main
示例4: main
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def main(args):
parser = argparse.ArgumentParser(
description=__doc__,
epilog='This is inefficient for long input, as StaSh pipes do not multitask'
)
parser.add_argument('file', help='files to display ("-" is stdin is default)', action='store', nargs='*')
parser.add_argument('-p', '--pageno', help='number screen pages cumulatively', action='store_true')
parser.add_argument('-l', '--lineno', help='number lines cumulatively', action='store_true')
parser.add_argument('-f', '--filename', help='label lines by filename', action='store_true')
parser.add_argument('-n', '--filelineno', '-#', help='number lines per file', action='store_true')
parser.add_argument(
'-s',
'--pagesize',
help='number of lines per screen page (0 for no pagination)',
action='store',
type=int,
default=40
) # TODO: use actual number of lines on screen for dynamic screen page size
parser.add_argument('-c', '--clear', help='clear terminal screen before each screen page', action='store_true')
ns = parser.parse_args(args)
ns.line = True
fmt = ' '.join('{' + var + '}' for var in 'pageno lineno filename filelineno line'.split() if getattr(ns, var))
more(ns.file, ns.pagesize, ns.clear, fmt)
示例5: input_stream
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def input_stream(files=()):
""" Handles input files similar to fileinput.
The advantage of this function is it recovers from errors if one
file is invalid and proceed with the next file
"""
fileinput.close()
try:
if not files:
for line in fileinput.input(files):
yield line, '', fileinput.filelineno()
else:
while files:
thefile = files.pop(0)
try:
for line in fileinput.input(thefile):
yield line, fileinput.filename(), fileinput.filelineno()
except IOError as e:
yield None, fileinput.filename(), e
finally:
fileinput.close()
示例6: print_error
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def print_error(self, error, line='',
filename=None, filelineno=None):
if self.should_ignore(error):
return
warn = self.should_warn(error)
if not filename:
filename = fileinput.filename()
if not filelineno:
filelineno = fileinput.filelineno()
if warn:
self.warning_count = self.warning_count + 1
else:
self.error_count = self.error_count + 1
self.log_error(error, line, filename, filelineno, warn)
示例7: test
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def test(self):
encoding = object()
result = fileinput.hook_encoded(encoding)
fake_open = InvocationRecorder()
original_open = builtins.open
builtins.open = fake_open
try:
filename = object()
mode = object()
open_result = result(filename, mode)
finally:
builtins.open = original_open
self.assertEqual(fake_open.invocation_count, 1)
args, kwargs = fake_open.last_invocation
self.assertIs(args[0], filename)
self.assertIs(args[1], mode)
self.assertIs(kwargs.pop('encoding'), encoding)
self.assertFalse(kwargs)
示例8: test_version
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def test_version(self):
message = "\nFound a different version at line %d or file %r: %r (may be %r)."
files = [os.path.join(self.source_dir, '__init__.py')]
if self.package_dir is not None:
files.extend([
os.path.join(self.package_dir, 'setup.py'),
os.path.join(self.package_dir, 'doc/conf.py'),
])
version = filename = None
for line in fileinput.input(files):
if fileinput.isfirstline():
filename = fileinput.filename()
lineno = fileinput.filelineno()
match = self.get_version.search(line)
if match is not None:
if version is None:
version = match.group(1).strip('\'\"')
else:
self.assertTrue(
version == match.group(1).strip('\'\"'),
message % (lineno, filename, match.group(1).strip('\'\"'), version)
)
示例9: __init__
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def __init__(self, filename, config, placeholders=False):
self.filename = filename
self.config = config
self.placeholders = placeholders
示例10: clear
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def clear(self, filename):
"""
Clear changes in a filename
"""
try:
del self.details[filename]
except KeyError:
# Probably the filename is not already there
return
示例11: filename
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def filename(self):
self.invocation_counts["filename"] += 1
return self.return_values["filename"]
示例12: test_state_is_None
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def test_state_is_None(self):
"""Tests fileinput.filename() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.filename()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state)
示例13: test_state_is_not_None
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def test_state_is_not_None(self):
"""Tests fileinput.filename() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filename() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
filename_retval = object()
instance = MockFileInput()
instance.return_values["filename"] = filename_retval
fileinput._state = instance
retval = fileinput.filename()
self.assertExactlyOneInvocation(instance, "filename")
self.assertIs(retval, filename_retval)
self.assertIs(fileinput._state, instance)
示例14: do_test_use_builtin_open
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def do_test_use_builtin_open(self, filename, mode):
original_open = self.replace_builtin_open(self.fake_open)
try:
result = fileinput.hook_compressed(filename, mode)
finally:
self.replace_builtin_open(original_open)
self.assertEqual(self.fake_open.invocation_count, 1)
self.assertEqual(self.fake_open.last_invocation,
((filename, mode), {}))
示例15: check_hashbang
# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import filename [as 别名]
def check_hashbang(line, filename, report):
# this check only runs on the first line
# maybe this should check for shell?
if (not filename.endswith(".sh") and not line.startswith("#!") and
not os.path.basename(filename).startswith('.')):
report.print_error(MESSAGES['E005'].msg, line)