推荐学习书目
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 · Jan 7, 2015 · 9415 views
    This topic created in 4168 days ago, the information mentioned may be changed or developed.
    
    先运行命令1,数据处理大约需要半分钟的时间,
    之后依次输入要处理的数据2并获取输出3.

    2和3这两个多次重复。

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

    不知道各位遇到这种情况是如何处理的……
    6 replies    2015-01-08 21:43:12 +08:00
    mengjue
        1
    mengjue  
       Jan 7, 2015
    try pexpect module
    clino
        2
    clino  
       Jan 7, 2015
    subprocess 可以啊,往 stdin 里面写不就行了吗?
    Delbert
        3
    Delbert  
    OP
       Jan 7, 2015
    @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  
       Jan 7, 2015
    问题出在 readlines
    https://docs.python.org/2/library/stdtypes.html#file.readlines
    这个借口是一直阻塞直到读完的

    你用楼上提到的 pexpect 吧,这个是专门做这种用途的吧
    brickgao
        5
    brickgao  
       Jan 7, 2015
    word2vec 的话,有人做了 python 的接口

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

    我把这个改改。
    多谢啦。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2892 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 05:46 · PVG 13:46 · LAX 22:46 · JFK 01:46
    ♥ Do have faith in what you're doing.