玩蛇网提供最新Python编程技术信息以及Python资源下载!

python使用subprocess出现问题

知网的下载工具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')

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd14158.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月15日 - 09时56分29秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules