Programing

파일 또는 STDIN에서 읽기

lottogame 2020. 12. 10. 08:28
반응형

파일 또는 STDIN에서 읽기


명령 줄에 주어진 인수를 구문 분석하기 위해 getopt를 사용하는 명령 줄 유틸리티를 작성했습니다. 또한 grep, cut 등과 같은 다른 유틸리티에있는 것과 같이 파일 이름을 선택적 인수로 사용하고 싶습니다. 따라서 다음과 같은 사용법을 갖고 싶습니다.

tool -d character -f integer [filename]

다음을 어떻게 구현할 수 있습니까?

  • 파일 이름이 주어지면 파일에서 읽습니다.
  • 파일 이름이 제공되지 않으면 STDIN에서 읽습니다.

가장 간단한 용어로 :

import sys
# parse command line
if file_name_given:
    inf = open(file_name_given)
else:
    inf = sys.stdin

이 시점 inf에서 파일에서 읽는 데 사용 합니다. 파일 이름이 주어 졌는지 여부에 따라 이것은 주어진 파일 또는 stdin에서 읽습니다.

파일을 닫아야 할 때 다음을 수행 할 수 있습니다.

if inf is not sys.stdin:
    inf.close()

그러나 대부분의 경우 종료 sys.stdin하면 닫아도 무해 합니다.


fileinput 함수의 모듈은 당신이 원하는 것을 할 수 있습니다 - 비 - 옵션 인수에 가정 args한 후 :

import fileinput
for line in fileinput.input(args):
    print line

args비어 있으면 fileinput.input()stdin에서 읽습니다. 그렇지 않으면 Perl과 유사한 방식으로 각 파일에서 차례로 읽습니다 while(<>).


나는 컨텍스트 관리자를 사용하는 일반적인 관용구를 좋아하지만 (너무) 사소한 해결책은 내가 피하고 싶은 성명에서 sys.stdin벗어나면 끝납니다 with.

이 답변 에서 차용 하면 다음 과 같은 해결 방법이 있습니다.

import sys
import contextlib

@contextlib.contextmanager
def _smart_open(filename, mode='Ur'):
    if filename == '-':
        if mode is None or mode == '' or 'r' in mode:
            fh = sys.stdin
        else:
            fh = sys.stdout
    else:
        fh = open(filename, mode)
    try:
        yield fh
    finally:
        if filename is not '-':
            fh.close()

if __name__ == '__main__':
    args = sys.argv[1:]
    if args == []:
        args = ['-']
    for filearg in args:
        with _smart_open(filearg) as handle:
            do_stuff(handle)

나는 당신이 비슷한 것을os.dup() 얻을 수 있다고 생각 하지만 내가 그것을 위해 요리 한 코드는 더 복잡하고 마법적인 것으로 판명되었지만 위의 내용은 다소 투박하지만 매우 간단합니다.


To make use of python's with statement, one can use the following code:

import sys
with open(sys.argv[1], 'r') if len(sys.argv) > 1 else sys.stdin as f:
    # read data using f
    # ......

I prefer to use "-" as an indicator that you should read from stdin, it's more explicit:

import sys
with open(sys.argv[1], 'r') if sys.argv[1] is not "-" else sys.stdin as f:
    pass # do something here

Not a direct answer but related.

Normally when you write a python script you could use the argparse package. If this is the case you can use:

parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

and here we set default to sys.stdin;

so If there is a file it will read it , and if not it will take the input from stdin "Note: that we are using positional argument in the example above"

for more visit: https://docs.python.org/2/library/argparse.html#nargs


Something like:

if input_from_file:
    f = open(file_name, "rt")
else:
    f = sys.stdin
inL = f.readline()
while inL:
    print inL.rstrip()
    inL = f.readline()

참고URL : https://stackoverflow.com/questions/1744989/read-from-file-or-stdin

반응형