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 |