2017-02-24 76 views
0

我找綁定我在Python機器上的一個文本文件到一個端口的方式,以相同的方式什麼的流動Linux命令做綁定文本文件到本地端口來讀取它

cat myfile.txt | pv -l -L 2000 -q | nc -lk 9999 

我想在Windows上這樣,所以我不能直接使用上述命令。我想這樣做,因爲那時我有另一個Python代碼(使用pyspark),它從該端口讀取數據作爲流。

data = StreamingContext(sc, 1).socketTextStream("localhost", 9999) 

回答

1

https://docs.python.org/2/library/socket.html可能是相關的文檔。

我不知道什麼pyspark,但我的猜測東西沿着這些路線:

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind(('', 9999)) 
s.listen(1) 
con, adr = s.accept() 
with open('myfile.txt') as f: 
    for line in f: 
     con.sendall(line) 
con.close() 

應該工作。它逐行發送,可能適用於你的用例(我注意到它是一個文本文件)。

如果您想一點統計的同時,你會被打印:

from __future__ import print_function 
import sys 
import socket 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

s.bind(('', 9999)) 
s.listen(1) 
print('listening') 
con, adr = s.accept() 
print('connected') 

with open('myfile.txt') as f: 
    f.seek(0,2) # go to end of file 
    filesize = f.tell() 
    f.seek(0) 
    sent = 0 

    for line in f: 
     con.sendall(line) 
     sent += len(line) 
     print('%s of %s' % (sent, filesize), end='\r') 
     sys.stdout.flush() 

con.close() 

此代碼發送的文件,然後關閉。如果您希望它重複發送該文件,或將其發送給多個客戶端,則可以將其擴展以完成此操作,但它要複雜一點。