python3 os.spawn及管道用法实例(进程间通信和python虚拟终端结合)

import os, time, sys, ptypipe_name0pipe_test0pipe_name1pipe_test1def read(fd):time.sleep(0.01)dataos.read(fd, 2



import os, time, sys, pty
pipe_name0 = 'pipe_test0'
pipe_name1 = 'pipe_test1'
def read(fd):
    time.sleep(0.01)
    data = os.read(fd, 2048) # 444444444读取回显内容 
    pipein1 = os.open(pipe_name1, os.O_WRONLY)
    os.write(pipein1,data) # 555555555写入管道1
    return data  # 必须有返回值

def child():
    pipeout0 = os.open(pipe_name0, os.O_RDONLY)
    os.dup2(pipeout0, 0)  # 22222222222读取管道0内容,复制到标准输入
    pty.spawn('/usr/bin/nc-cli', read) #333333333终端回显内容回调read函数

def parent():
    pipein0 = os.open(pipe_name0, os.O_WRONLY)
    pipeout1 = os.open(pipe_name1, os.O_RDONLY)
    os.write(pipein0, b"edit running\n vrf main snmp static-info name wsqtest\n commit\n exit\n exit\n ") #父进程输入终端命令,# 1111111111写入管道0
    time.sleep(0.03)
    os.read(pipeout1,2048) # 666666666读取管道1内容,得到终端回显
    os.read(pipeout1,2048)

if not os.path.exists(pipe_name0):
    os.mkfifo(pipe_name0)
if not os.path.exists(pipe_name1):
    os.mkfifo(pipe_name1)  
pid = os.fork()    
if pid != 0: # 两次判断:第一次执行if,第二次执行else
    parent()
else:       
    child()

发布者:admin,转转请注明出处:http://www.yc00.com/web/1754581238a5177961.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信