python子进程进行kinit认证_Python子进程和用户交互

I'm working on a GUI front end in Python 2.6 and usually it's fairly simple: you use subprocess.call() or subprocess.Popen() to issue the command and wait for it to finish or react to an error. What do you do if you have a program that stops and waits for user interaction? For example, the program might stop and ask the user for an ID and password or how to handle an error?

c:\> parrot

Military Macaw - OK

Sun Conure - OK

African Grey - OK

Norwegian Blue - Customer complaint!

(r) he's Resting, (h) [Hit cage] he moved, (p) he's Pining for the fjords

So far everything I've read tells you how to read all output from a program only AFTER it's finished, not how to deal with output while the program is still running. I can't install new modules (this is for a LiveCD) and I'll be dealing with user input more than once.

解决方案

Check out the subprocess manual. You have options with subprocess to be able to redirect the stdin, stdout, and stderr of the process you're calling to your own.

from subprocess import Popen, PIPE, STDOUT

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]

print grep_stdout

You can also interact with a process line by line. Given this as prog.py:

import sys

print 'what is your name?'

sys.stdout.flush()

name = raw_input()

print 'your name is ' + name

sys.stdout.flush()

You can interact with it line by line via:

>>> from subprocess import Popen, PIPE, STDOUT

>>> p = Popen(['python', 'prog.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

>>> p.stdout.readline().rstrip()

'what is your name'

>>> p.communicate('mike')[0].rstrip()

'your name is mike'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值