Read arguments from filename or stdin
#!/usr/bin/env python3
"""
If the argument is a file, the contents of the file,
Otherwise print the arguments
"""
import sys
import fileinput
from pathlib import Path
if Path(sys.argv[1]).exists(): #If the first argument is a file
for line in fileinput.input(): #Print the contents of the file line by line
print('file input')
print(line)
else: #If the first argument is not a file
for i in sys.argv[1:]: #Print the argument string
print('args input')
print(i)
Execution result
$ python stdin_test.py hoge.txt fuga.txt
file input
MYNAME!
file input
HERO!!
$ python stdin_test.py 1 2 3
args input
1
args input
2
args input
3
Since sys.argv
is returned as a list, I used it so that the result offileinput.input ()
is also returned in list format.
Read arguments from filename or stdin and return as a list
if Path(sys.argv[1]).exists(): #If the first argument is a file
ARGV = [
line.replace('\n', '') for line in fileinput.input() #Delete line breaks
if line != '\n' #Delete blank lines
]
else: #If the first argument is not a file
ARGV = sys.argv[1:]
Python official doc
Recommended Posts