【发布时间】:2014-08-10 05:17:30
【问题描述】:
我有一个函数可以读取二进制文件并将每个字节转换为相应的字符序列。例如,0x05 变为 'AACC',0x2A 变为 'AGGG' 等等......读取文件并转换字节的函数目前是线性函数,由于要转换的文件在 25kb 和 2Mb 之间,这可能需要相当长的时间一会儿。
因此,我正在尝试使用多处理来划分任务并希望提高速度。但是,我就是无法让它工作。下面是线性函数,虽然速度很慢;
def fileToRNAString(_file):
if (_file and os.path.isfile(_file)):
rnaSequences = []
blockCount = 0
blockSize = 2048
printAndLog("!", "Converting %s into RNA string (%d bytes/block)" % (_file, blockSize))
with open(_file, "rb") as hFile:
buf = hFile.read(blockSize)
while buf:
decSequenceToRNA(blockCount, buf, rnaSequences)
blockCount = blockCount + 1
buf = hFile.read(blockSize)
else:
printAndLog("-", "Could not find the specified file. Please verify that the file exists:" + _file)
return rnaSequences
注意:函数 'decSequenceToRNA' 读取缓冲区并将每个字节转换为所需的字符串。执行时,该函数返回一个包含块号和字符串的元组,例如(1, 'ACCGTAGATTA...') 最后,我有一个可用的这些元组的数组。
我已尝试将函数转换为使用 Python 的多处理;
def fileToRNAString(_file):
rnaSequences = []
if (_file and os.path.isfile(_file)):
blockCount = 0
blockSize = 2048
printAndLog("!", "Converting %s into RNA string (%d bytes/block)" % (_file, blockSize))
workers = []
with open(_file, "rb") as hFile:
buf = hFile.read(blockSize)
while buf:
p = Process(target=decSequenceToRNA, args=(blockCount, buf, rnaSequences))
p.start()
workers.append(p)
blockCount = blockCount + 1
buf = hFile.read(blockSize)
for p in workers:
p.join()
else:
printAndLog("-", "Could not find the specified file. Please verify that the file exists:" + _file)
return rnaSequences
但是,似乎没有任何进程启动,因为当运行此函数时,会返回一个空数组。 'decSequenceToRNA' 中打印到控制台的任何消息都不会显示;
>>>fileToRNAString(testfile)
[!] Converting /root/src/amino56/M1H2.bin into RNA string (2048 bytes/block).
与这里的question 不同,我正在运行 Linux shiva 3.14-kali1-amd64 #1 SMP Debian 3.14.5-1kali1 (2014-06-07) x86_64 GNU/Linux 并使用PyCrust 在 Python 版本:2.7.3 上测试函数。我正在使用以下软件包:
import os
import re
import sys
import urllib2
import requests
import logging
import hashlib
import argparse
import tempfile
import shutil
import feedparser
from multiprocessing import Process
我想知道为什么我的代码不起作用,或者我是否在其他地方遗漏了一些东西以使流程正常工作。也对改进代码的建议持开放态度。下面是 'decSequenceToRNA' 供参考:
def decSequenceToRNA(_idxSeq, _byteSequence, _rnaSequences):
rnaSequence = ''
printAndLog("!", "Processing block %d (%d bytes)" % (_idxSeq, len(_byteSequence)))
for b in _byteSequence:
rnaSequence = rnaSequence + base10ToRNA(ord(b))
printAndLog("+", "Block %d completed. RNA of %d nucleotides generated." % (_idxSeq, len(rnaSequence)))
_rnaSequences.append((_idxSeq, rnaSequence))
【问题讨论】:
-
你是如何执行脚本的?它只是来自 bash 提示符吗?
标签: python linux parallel-processing multiprocessing