在Python中,获取函数或方法的返回值通常很简单,只需调用该函数或方法并将返回值赋给一个变量。以下是几种常见的方法来读取返回值:
直接调用函数:
```python
def my_function():
return "Hello, World!"
result = my_function()
print(result) 输出:Hello, World!
使用`return`语句:
```python
def my_function():
return "Hello, World!"
result = my_function()
print(result) 输出:Hello, World!
使用`concurrent.futures`模块:
```python
import concurrent.futures
def task():
return "Hello, World!"
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(task)
result = future.result()
print(result) 输出:Hello, World!
使用`threading`模块:
```python
import threading
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self.result = None
def run(self):
self.result = "Hello, World!"
thread = MyThread()
thread.start()
thread.join()
print(thread.result) 输出:Hello, World!
使用`subprocess`模块执行系统命令:
```python
import subprocess
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
print(result.stdout) 输出系统命令的输出结果
以上是获取Python函数或方法返回值的一些常见方法。请根据您的具体需求选择合适的方法