「Python cat.py」の版間の差分
Moutaku3dayo (トーク | 投稿記録) (ページの作成:「<syntaxhighlight lang="python" line> import argparse import sys def cat(input_files, number_lines): """ Display the content of files or standard input. :param input_files: List of input file paths or None for standard input. :param number_lines: If True, number the output lines. """ line_number = 1 def process_file(file): nonlocal line_number try: for line in file: if number_lines:…」) |
Moutaku3dayo (トーク | 投稿記録) 編集の要約なし |
||
55行目: | 55行目: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== 関連項目 == | |||
* [[Python cat.py]] | |||
* [[Python cut.py]] | |||
* [[Python sort.py]] | |||
* [[Python uniq.py]] | |||
* https://chatgpt.com/ | |||
[[Category:chatgpt]] | |||
[[Category:Python]] |
2025年3月28日 (金) 21:29時点における最新版
import argparse
import sys
def cat(input_files, number_lines):
"""
Display the content of files or standard input.
:param input_files: List of input file paths or None for standard input.
:param number_lines: If True, number the output lines.
"""
line_number = 1
def process_file(file):
nonlocal line_number
try:
for line in file:
if number_lines:
print(f"{line_number:6} {line.rstrip()}")
line_number += 1
else:
print(line, end="")
except IOError as e:
print(f"Error reading file: {e}", file=sys.stderr)
if not input_files:
# No files provided, read from standard input
process_file(sys.stdin)
else:
for file_path in input_files:
try:
with open(file_path, "r") as file:
process_file(file)
except FileNotFoundError:
print(f"cat: {file_path}: No such file or directory", file=sys.stderr)
except IOError as e:
print(f"cat: {file_path}: Error: {e}", file=sys.stderr)
def main():
parser = argparse.ArgumentParser(description="Python implementation of the cat command.")
parser.add_argument("files", metavar="FILE", nargs="*", help="Files to display. Reads standard input if no files are provided.")
parser.add_argument("-n", "--number", action="store_true", help="Number the output lines.")
args = parser.parse_args()
cat(input_files=args.files, number_lines=args.number)
if __name__ == "__main__":
main()