namhyung / uftrace

Function graph tracer for C/C++/Rust/Python
https://uftrace.github.io/slide/
GNU General Public License v2.0
2.92k stars 419 forks source link

python: improve python trace user experience #1891

Open yihong0618 opened 4 months ago

yihong0618 commented 4 months ago

Add a simple way to support trace python file without shebang and be an executable file.

Fixed: #1890

with this path we can trace python file just like

g.py like

import sys
import urllib.request

def open_file(name):
    try:
        return open(name)
    except:
        return urllib.request.urlopen(name)

def count_word(file_obj, word):
    n = 0
    content = str(file_obj.read())
    for ln in content.split('\n'):
        n += ln.count(word)
    return n

if __name__ == '__main__':
    url = 'https://github.com/namhyung/uftrace'
    word = 'uftrace'
    if len(sys.argv) > 1:
        url = sys.argv[1]
    if len(sys.argv) > 2:
        word = sys.argv[2]

    f = open_file(url)
    n = count_word(f, word)
    print(n)

then

uftrace g.py