Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32768
| References | <CAF_E5JYQd5aPnjtpjiHVBpsro-85pV-4zQA9oaNdPUkhOkAZ9g@mail.gmail.com> <k7892k$g9d$1@ger.gmane.org> |
|---|---|
| Date | 2012-11-05 13:16 +0000 |
| Subject | Re: accepting file path or file object? |
| From | andrea crotti <andrea.crotti.0@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3281.1352121410.27098.python-list@python.org> (permalink) |
2012/11/5 Peter Otten <__peter__@web.de>: > I sometimes do something like this: > > $ cat xopen.py > import re > import sys > from contextlib import contextmanager > > @contextmanager > def xopen(file=None, mode="r"): > if hasattr(file, "read"): > yield file > elif file == "-": > if "w" in mode: > yield sys.stdout > else: > yield sys.stdin > else: > with open(file, mode) as f: > yield f > > def grep(stream, regex): > search = re.compile(regex).search > return any(search(line) for line in stream) > > if len(sys.argv) == 1: > print grep(["alpha", "beta", "gamma"], "gamma") > else: > with xopen(sys.argv[1]) as f: > print grep(f, sys.argv[2]) > $ python xopen.py > True > $ echo 'alpha beta gamma' | python xopen.py - gamma > True > $ echo 'alpha beta gamma' | python xopen.py - delta > False > $ python xopen.py xopen.py context > True > $ python xopen.py xopen.py gamma > True > $ python xopen.py xopen.py delta > False > $ > > > -- > http://mail.python.org/mailman/listinfo/python-list That's nice thanks, there is still the problem of closing the file handle but that's maybe not so important if it gets closed at termination anyway..
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: accepting file path or file object? andrea crotti <andrea.crotti.0@gmail.com> - 2012-11-05 13:16 +0000
csiph-web