I usually do this in Perl:
我通常在Perl中這樣做:
whatever.pl
while(<>) {
#do whatever;
}
then cat foo.txt | whatever.pl
然后cat foo.txt | whatever.pl
Now, I want to do this in Python. I tried sys.stdin
but I have no idea how to do as I have done in Perl. How can I read the input?
現在,我想用Python做到這一點。我試過sys.stdin,但我不知道怎么做,就像我在Perl中做的那樣。我該如何閱讀輸入?
Try this:
import fileinput
for line in fileinput.input():
process(line)
import sys
def main():
for line in sys.stdin:
print line
if __name__=='__main__':
sys.exit(main())
Something like this:
像這樣的東西:
import sys
for line in sys.stdin:
# whatever
import sys
for line in sys.stdin:
# do stuff w/line
I hate to beat a dead horse, but may I suggest using a pure function?
我討厭擊敗死馬,但我可以建議使用純粹的功能嗎?
import sys
def main(stdin):
for line in stdin:
print("You said: " + line.strip())
if __name__ == "__main__":
main(sys.stdin)
This approach is nice because main is dependent purely on its input and you can unit test it with anything that obeys the line-delimited input stream paradigm.
這種方法很好,因為main完全依賴於它的輸入,你可以用符合行划分輸入流范例的任何東西對它進行單元測試。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/04/03/f3daa89ed41f59afb39fac07e85f83ec.html。