推荐学习书目
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
yangzh
V2EX  ›  Python

如何在 terminal 运行 python 脚本,显示出 interactive 的结果?

  •  
  •   yangzh · Dec 18, 2013 · 7776 views
    This topic created in 4554 days ago, the information mentioned may be changed or developed.
    比如说,我有这么一个 test.py:
    ```
    print 'hello world!'
    1+1
    a=3
    a
    ```

    如果我在 terminal 运行的话:
    ```
    $ python test.py
    hello world!
    ```

    我想达成这么一个效果,在 terminal 运行:
    ```
    $ magicpython test.py
    >>> print 'hello world!'
    hello world!
    >>> 1+1
    2
    >>> a=3
    >>> a
    3
    ```

    我想知道的就是 magicpython 这个程序怎样写。原生的 python 和 ipython 都没有这个效果。
    8 replies    1970-01-01 08:00:00 +08:00
    felix021
        1
    felix021  
       Dec 18, 2013   ❤️ 1
    yangzh
        2
    yangzh  
    OP
       Dec 18, 2013
    @felix021 这位仁兄亲自操刀一个。真是感动。虽然我以为会有什么库是支持这个需求的。
    felix021
        3
    felix021  
       Dec 18, 2013
    @yangzh 纯粹闲的蛋疼。。本来想用pty.spawn来搞的,但是退出不了,所以还是用compiler自己搞。
    polythene
        4
    polythene  
       Dec 18, 2013   ❤️ 2
    @yangzh 如果你调试过python程序,就应该知道pdb这个库正巧满足你的需求
    python -m pdb test.py
    xiaket
        5
    xiaket  
       Dec 19, 2013   ❤️ 1
    import code
    code.interact(local=locals())

    代码太短懒得贴gist了, python脚本里这两句就够了.
    yangzh
        6
    yangzh  
    OP
       Dec 19, 2013
    @polythene 这么便捷?!谢谢哈!我不是专业的,只是写了一些段程序,用土办法 print 来调试。

    @xiaket 我回家试一下!
    yangzh
        7
    yangzh  
    OP
       Dec 19, 2013
    @polythene 呃,我试了一下,其实和我显示的效果相差挺大的。。。虽然原理应该差不多。
    mckelvin
        8
    mckelvin  
       Jan 18, 2014 via Android
    先开python或ipython,再execfile('test.py')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5464 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 07:07 · PVG 15:07 · LAX 00:07 · JFK 03:07
    ♥ Do have faith in what you're doing.