2017-02-14 78 views
2

理想情況下,我想要做的就是在Python中複製這個bash管道(我在這裏使用cut來表示一些數據的任意轉換,實際上我想用pandas來做到這一點) :從Python的ftplib管道不阻塞

curl ftp://hgdownload.cse.ucsc.edu/goldenPath/hg38/database/refFlat.txt.gz | gunzip | cut -f 1,2,4 

我可以用Python語言編寫下面的代碼,達到同樣的目的

# Download the zip file into memory 
file = io.BytesIO() 
ftp = ftplib.FTP('hgdownload.cse.ucsc.edu') 
ftp.retrbinary(f'RETR goldenPath/{args.reference}/database/refFlat.txt.gz', file.write) 

# Unzip the gzip file 
table = gzip.GzipFile(fileobj=file) 

# Read into pandas 
df = pd.read_csv(table) 

然而,ftp.retrbinary()調用阻塞,並等待整個下載。我想要的是有一個長的二進制流,以FTP文件作爲源,gunzip作爲過濾器,並且pd.read_csv()作爲接收器,全部同時處理數據,就像在我的bash管道中一樣。有沒有辦法阻止retrbinary()阻止?

我意識到這可能是不可能的,因爲python不能使用多個線程。這是真的?如果是的話,我可以使用multiprocessingasync或其他語言功能來實現這一目標的同時管道

編輯:改變storbinaryretrbinary,這是一個錯字,問題依然屹立

+0

Python可以完全使用多個線程。你正在考慮GIL,這是不同的。 –

回答

0

您應該能夠將文件直接下載到GZipFile

gzipfile = gzip.GzipFile() 
ftp.storbinary(f'RETR goldenPath/{args.reference}/database/refFlat.txt.gz', gzipfile.write)