V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Delbert
V2EX  ›  Python

Python 如何获取交互式命令行的输出?

  •  
  •   Delbert ·
    cnDelbert · 2015-01-07 15:36:23 +08:00 · 8582 次点击
    这是一个创建于 3390 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    先运行命令1,数据处理大约需要半分钟的时间,
    之后依次输入要处理的数据2并获取输出3.

    2和3这两个多次重复。

    试过os.system Popen 还有subprocess好像都不能在1之后再输入2,无法交互式处理命令行,也就无法获取到3

    不知道各位遇到这种情况是如何处理的……
    6 条回复    2015-01-08 21:43:12 +08:00
    mengjue
        1
    mengjue  
       2015-01-07 15:42:52 +08:00
    try pexpect module
    clino
        2
    clino  
       2015-01-07 15:43:15 +08:00
    subprocess 可以啊,往 stdin 里面写不就行了吗?
    Delbert
        3
    Delbert  
    OP
       2015-01-07 16:17:37 +08:00
    @clino
    @mengjue
    ```python
    concept_file = open('concepts.txt', 'rt')
    p = Popen('./distance vectors.bin', stdin=PIPE,stdout=PIPE, bufsize=1)
    time.sleep(30)
    word = concept_file.readline()
    print(word)
    Popen.stdin = word
    Popen.stdin = 'EXIT'
    print(p.stdout.readlines())
    concept_file.close()
    ```
    之后就卡住了,一动不动,换成read()和readline()也都一样。。。。
    clino
        4
    clino  
       2015-01-07 16:26:29 +08:00
    问题出在 readlines
    https://docs.python.org/2/library/stdtypes.html#file.readlines
    这个借口是一直阻塞直到读完的

    你用楼上提到的 pexpect 吧,这个是专门做这种用途的吧
    brickgao
        5
    brickgao  
       2015-01-07 23:51:11 +08:00
    word2vec 的话,有人做了 python 的接口

    https://pypi.python.org/pypi/word2vec
    Delbert
        6
    Delbert  
    OP
       2015-01-08 21:43:12 +08:00
    @brickgao 郁闷死了。今天装了一整天的这个……
    这个需要numpy,作者github上没写。
    numpy在python2.7上死活装不上,
    在Python3.4上通过make gcc好不容易装上了
    word2vec直接import不进去。而且里面的函数是2.x的,我看到有xrange了……不一定能用……唉

    我把这个改改。
    多谢啦。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1009 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:29 · PVG 03:29 · LAX 12:29 · JFK 15:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.