![](/img/trans.png)
[英]Python - How to take input from command line and pipe it into socket.gethostbyaddr(“”)
[英]How to pipe input to python line by line from linux program?
我想將ps -ef
的輸出逐行傳送到 python。
我正在使用的腳本是這個 (first.py) -
#! /usr/bin/python
import sys
for line in sys.argv:
print line
不幸的是,“行”被分成由空格分隔的單詞。 所以,例如,如果我這樣做
echo "days go by and still" | xargs first.py
我得到的輸出是
./first.py
days
go
by
and
still
如何編寫腳本以使輸出為
./first.py
days go by and still
?
我建議不要使用命令行參數,而是從標准輸入( stdin
) 中讀取。 Python 有一個簡單的習慣用法,用於在stdin
處迭代行:
import sys
for line in sys.stdin:
sys.stdout.write(line)
我的使用示例(上面的代碼保存到iterate-stdin.py
):
$ echo -e "first line\nsecond line" | python iterate-stdin.py
first line
second line
以你的例子:
$ echo "days go by and still" | python iterate-stdin.py
days go by and still
您想要的是popen
,它可以像讀取文件一樣直接讀取命令的輸出:
import os
with os.popen('ps -ef') as pse:
for line in pse:
print line
# presumably parse line now
請注意,如果您想要更復雜的解析,則必須深入研究subprocess.Popen
的文檔。
另一種方法是使用input()
函數(代碼適用於 Python 3)。
while True:
try:
line = input()
print('The line is:"%s"' % line)
except EOFError:
# no more information
break
答案與Jan-Philip Gehrcke 博士得到的答案之間的區別在於,現在每一行的末尾都沒有換行符 (\\n)。
我知道這真的過時了,但你可以試試
#! /usr/bin/python
import sys
print(sys.argv, len(sys.argv))
if len(sys.argv) == 1:
message = input()
else:
message = sys.argv[1:len(sys.argv)]
print('Message:', message)
我是這樣測試的:
$ ./test.py
['./test.py'] 1
this is a test
Message: this is a test
$ ./test.py this is a test
['./test.py', 'this', 'is', 'a', 'test'] 5
Message: ['this', 'is', 'a', 'test']
$ ./test.py "this is a test"
['./test.py', 'this is a test'] 2
Message: ['this is a test']
$ ./test.py 'this is a test'
['./test.py', 'this is a test'] 2
Message: ['this is a test']
$ echo "This is a test" | ./test.py
['./test.py'] 1
Message: This is a test
或者,如果您希望消息每次都是一個字符串,那么
message = ' '.join(sys.argv[1:len(sys.argv)])
會在第 8 行做到這一點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.