python使用subprocess的问题
高洛峰
高洛峰 2017-04-18 10:17:17
[Python讨论组]

知网的下载工具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中该如何控制呢?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
ringa_lee

使用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')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号