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