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

问 有没有一种方法可以打印出python中的一段特定的代码

  •  
  •   Hualin · 2012-08-01 23:17:20 +08:00 · 2654 次点击
    这是一个创建于 4283 天前的主题,其中的信息可能已经有所发展或是发生改变。
    大家好,请教一个问题。
    有没有一种方法可以在 python 程序正在运行的时候打印出该语句之前某一段 python 的代码?
    比如:
    ##code##
    from pylab import *
    A = zeros(10, dtype = bool)
    B = ones(10, dtype = bool)
    R = A & B
    print R
    ##code##

    我想让程序在控制台输出类似 R = A & B,这样的提示。除了直接在程序中直接写 print 'A & B',有没有比较直接的方法?因为这种逻辑条件可能比较复杂,我想输出这些 statement 在控制台以供查看。
    6 条回复    1970-01-01 08:00:00 +08:00
    Hualin
        1
    Hualin  
    OP
       2012-08-01 23:19:14 +08:00
    不知道可能不可能,感觉有点不靠谱。
    dreampuf
        2
    dreampuf  
       2012-08-01 23:25:17 +08:00   ❤️ 2
    将目标代码封装成为代码。
    执行前输出 inspect.getsource(targetfunction)
    Hualin
        3
    Hualin  
    OP
       2012-08-01 23:50:10 +08:00
    @dreampuf 刚实验了下,似乎和想象的不大一样,这个 code object 只能是写道文件里的 function method class 等,不能直接是某一段代码语句。不过可以把这个 string trim一下。
    clowwindy
        4
    clowwindy  
       2012-08-03 15:49:42 +08:00   ❤️ 1
    不知道是不是你想要的

    https://gist.github.com/3245499

    $ python test_file.py

    # foobar
    frame = inspect.currentframe()
    with open(frame.f_code.co_filename, 'rb') as f:
    print ''.join(f.readlines()[frame.f_lineno - LINES_TO_PRINT:])
    clowwindy
        5
    clowwindy  
       2012-08-03 15:51:47 +08:00
    重贴一次,没有编辑回复/预览功能有时真不方便 @Livid

    http://gist.github.com/3245499
    Livid
        6
    Livid  
    MOD
       2012-08-03 15:53:26 +08:00
    @clowwindy 嗯,回复预览确实应该有。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3627 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:47 · PVG 08:47 · LAX 17:47 · JFK 20:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.