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
yangzh
V2EX  ›  Python

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

  •  
  •   yangzh · 2013-12-18 17:09:56 +08:00 · 7031 次点击
    这是一个创建于 3781 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如说,我有这么一个 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 条回复    1970-01-01 08:00:00 +08:00
    felix021
        1
    felix021  
       2013-12-18 19:53:13 +08:00   ❤️ 1
    yangzh
        2
    yangzh  
    OP
       2013-12-18 20:07:31 +08:00
    @felix021 这位仁兄亲自操刀一个。真是感动。虽然我以为会有什么库是支持这个需求的。
    felix021
        3
    felix021  
       2013-12-18 20:36:18 +08:00
    @yangzh 纯粹闲的蛋疼。。本来想用pty.spawn来搞的,但是退出不了,所以还是用compiler自己搞。
    polythene
        4
    polythene  
       2013-12-18 23:15:47 +08:00   ❤️ 2
    @yangzh 如果你调试过python程序,就应该知道pdb这个库正巧满足你的需求
    python -m pdb test.py
    xiaket
        5
    xiaket  
       2013-12-19 08:38:24 +08:00   ❤️ 1
    import code
    code.interact(local=locals())

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

    @xiaket 我回家试一下!
    yangzh
        7
    yangzh  
    OP
       2013-12-19 11:54:45 +08:00
    @polythene 呃,我试了一下,其实和我显示的效果相差挺大的。。。虽然原理应该差不多。
    mckelvin
        8
    mckelvin  
       2014-01-18 10:00:47 +08:00 via Android
    先开python或ipython,再execfile('test.py')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   996 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:30 · PVG 04:30 · LAX 13:30 · JFK 16:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.