Can you open stdin as a file on MS Windows in Python? -
Can you open stdin as a file on MS Windows in Python? -
on linux, i'm using supbprocess.popen run app. command line of app requires path input file. learned can pass path /dev/stdin command line, , utilize python's subproc.stdin.write() send input subprocess.
import subprocess kw['shell'] = false kw['executable'] = '/path/to/myapp' kw['stdin'] = subprocess.pipe kw['stdout'] = subprocess.pipe kw['stderr'] = subprocess.pipe subproc = subprocess.popen(['','-i','/dev/stdin'],**kw) inbuff = [u'my lines',u'of text',u'to process',u'go here'] outbuff = [] conditionbuff = [] def processdata(inbuff,outbuff,conditionbuff): i,line in enumerate(inbuff): subproc.stdin.write('%s\n'%(line.encode('utf-8').strip())) line = subproc.stdout.readline().strip().decode('utf-8') if 'condition' in line: conditionbuff.append(line) else: outbuff.append(line) processdata(inbuff,outbuff,conditionbuff)
there's ms windows version of app. there equivalent on ms windows using /dev/stdin or linux (posix) specific solution?
if myapp
treats -
special filename denotes stdin then:
from subprocess import pipe, popen p = popen(['/path/to/myapp', '-i', '-'], stdin=pipe, stdout=pipe) stdout, _ = p.communicate('\n'.join(inbuff).encode('utf-8')) outbuff = stdout.decode('utf-8').splitlines()
if can't pass -
utilize temporary file:
import os import tempfile tempfile.namedtemporaryfile(delete=false) f: f.write('\n'.join(inbuff).encode('utf-8')) p = popen(['/path/to/myapp', '-i', f.name], stdout=pipe) outbuff, conditionbuff = [], [] line in iter(p.stdout.readline, ''): line = line.strip().decode('utf-8') if 'condition' in line: conditionbuff.append(line) else: outbuff.append(line) p.stdout.close() p.wait() os.remove(f.name) #xxx add together try/finally proper cleanup
to suppress stderr
pass open(os.devnull, 'wb')
stderr
popen
.
python windows linux stdin
Comments
Post a Comment