如何将 self 参数传递给 python cProfile

How do I pass in a self argument to python cProfile

我正在尝试将 cProfiling 与 python 结合使用。

我的python项目目录结构如下:

my-project
├── src
│   ├── lib 
│       └── app
│           └── data
│               └── car_sim.py
│
│
│
│
├── ptests 
│   ├── src 
│       └── lib 
│           └── app
│               └── data
│                   └── cprofile_test.py

我在 car_sim.py 中有一个我想要 cprofile 的函数,它叫做 "sim_text"。它包含一个名为:

的函数
#car_sim.py
import os

class RootSimulator:

    def sim_text(self, text):
            return text

我在里面使用下面的代码cprofile_test.py:

#cprofile_test.py
import cProfile
import pstats
import io

import src.lib.app.data.car_sim as car_sim_functions


pr = cProfile.Profile()
pr.enable()
text = 'my blabla sentence' #i can pass in this text below i guess...

#how do i pass to the below????!!
my_result = car_sim_functions.RootSimulator.sim_text()

pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()

with open('test.txt', 'w+') as f:
    f.write(s.getvalue())

现在...当我 运行 它使用命令

python -m cProfile ptests/src/lib/app/data/cprofile_test.py

我收到以下错误:

TypeError: sim_text() missing 2 required positional arguments: 'self' and 'text'

我的问题是...它需要 2 个参数,那么我该如何传递 "self" 参数。对于第二个参数,"text" 我可以传入一个值没问题。

class RootSimulator:

    def sim_text(self, text):
            return text

RootSimulator 的实例上定义一个实例方法。您正在尝试从 class 本身调用 sim_text。您需要创建一个实例:

simulator = car_sim_functions.RootSimulator()
my_result = simulator.sim_text()

如果 sim_text() 实际上不需要附加到模拟器的实例,也许您根本不需要 class(只需将其设为普通函数),或者您可以使它成为静态方法:

class RootSimulator:

    @staticmethod
    def sim_text(text):
            return text

请注意,它不再需要 self