Python custom delimiter for read or readline -
i interacting subprocess , trying detect when ready input. problem having read or readline functions rely on '\n' delimiter @ end of line, or eof yield. since subprocess never exits, there no eof in file object. since keyword want trigger off of not contain delimiter read , readline functions never yield. example:
'doing something\n' 'doing else\n' 'input>' since process never exits, read or read line never see eof or \n requires yield.
is there way read file object , set custom delimiter input>?
you can implement own readlines function , choose delimiter yourself:
def custom_readlines(handle, line_separator="\n", chunk_size=64): buf = "" # storage buffer while not handle.closed: # while our handle open data = handle.read(chunk_size) # read `chunk_size` sized data passed handle if not data: # no more data... break # break away... buf += data # add collected data internal buffer if line_separator in buf: # we've encountered separator chunks = buf.split(line_separator) buf = chunks.pop() # keep last entry in our buffer chunk in chunks: # yield rest yield chunk + line_separator if buf: yield buf # return last buffer if unfortunately, due python default buffering policies won't able grab large swaths of data if not provided process you're calling, can resort setting chunk_size 1 , read input character character. so, example, need is:
import subprocess proc = subprocess.popen(["your", "subprocess", "command"], stdout=subprocess.pipe) while chunk in custom_readlines(proc.stdout, ">", 1): print(chunk) # whatever want here... and should capture > subprocesses' stdout. can use multiple characters separators in version.
Comments
Post a Comment