python使用subprocess的问题

 溪边莎草 发布于 2022-10-30 00:46

知网的下载工具cnki-downloader想在python里调用,但是处理不来输入输出的问题。

from subprocess import *  


def get_output(p, line_no):
    for i in range(0, line_no):
        print (p.stdout.readline())
    p.stdout.flush()
def input_command(p, str_input):
    p.stdin.flush()
    print ("[Input]: " + str_input)

p =Popen('cnki-downloader.exe',stdin=PIPE,stdout=PIPE,bufsize=1,shell=True)

get_output(p, 13)
input_command(p, 'python')

获得输出的时候,'$ input anything you wanna search: '这一段要手动在任务管理器中把进程结束掉才出现。cnki-downloader一开始运行时有几秒是检查更新的,然后才能输入指令。请教python中该如何控制呢?

1 个回答
  • 使用expect能与子进程交互,比如:

    # This connects to the openbsd ftp site and
    # downloads the recursive directory listing.
    import pexpect
    child = pexpect.spawn('ftp ftp.openbsd.org')
    child.expect('Name .*: ')
    child.sendline('anonymous')
    child.expect('Password:')
    child.sendline('noah@example.com')
    child.expect('ftp> ')
    child.sendline('lcd /tmp')
    child.expect('ftp> ')
    child.sendline('cd pub/OpenBSD')
    child.expect('ftp> ')
    child.sendline('get README')
    child.expect('ftp> ')
    child.sendline('bye')
    2022-10-31 19:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有