Linux 的管線 Pipe 可以把多個指令配合使用, 實現很多功能。而 Python 要讀取 pipe 輸入, 只要透過 stdin 便可以實現, 例如:
1 2 3 4 5 6 |
#!/usr/bin/python import sys for line in sys.stdin: sys.stdout.write(line) |
以上幾行程式碼, 會讀取 pipe 的輸入, 然後逐行印出。上面的 line 就是每一行的內容, 例如假設以上程式名為 test.py, 可以這樣測試:
1 |
$ echo -e "line 1\nline 2" | ./test.py |
上面的例子需要在 pipe 輸入內容, 如果想直接在 Python 內執行指令, 並逐行讀取, 其中一個方法是透過 popen():
1 2 3 4 5 6 7 |
#!/usr/bin/python import os with os.popen('ls -l') as filelist: for line in filelist: print lin |