linux shell与python,Python脚本和linux shell之间的交互

#!/usr/bin/env python

import os

import pty

import sys

with open('log', 'ab') as file:

def read(fd):

data = os.read(fd, 1024)

file.write(data)

file.flush()

return data

pty.spawn([sys.executable, "test.py"], read)

或者你可以使用pexpect更多的灵活性:

import sys

import pexpect # $ pip install pexpect

with open('log', 'ab') as fout:

p = pexpect.spawn("python test.py")

p.logfile = fout # or .logfile_read

p.interact()

如果你的子进程不会缓冲它的输出(或者它不会干扰交互),并且它的输出打印到stdout或stderr,那么你可以尝试subprocess:

#!/usr/bin/env python

import sys

from subprocess import Popen, PIPE, STDOUT

with open('log','ab') as file:

p = Popen([sys.executable, '-u', 'test.py'],

stdout=PIPE, stderr=STDOUT,

close_fds=True,

bufsize=0)

for c in iter(lambda: p.stdout.read(1), ''):

for f in [sys.stdout, file]:

f.write(c)

f.flush()

p.stdout.close()

rc = p.wait()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值