要捕获shell()函数的输出,可以使用subprocess模块中的subprocess.run()函数。下面是一个示例代码:
import subprocess
def shell():
output = subprocess.run(["ls", "-l"], capture_output=True, text=True)
return output.stdout
result = shell()
print(result)
在上面的示例中,shell()函数使用subprocess.run()函数来运行"ls -l"命令,并将输出捕获到output变量中。通过设置capture_output=True和text=True参数,可以将输出以文本形式捕获到stdout属性中。然后,将捕获的输出返回给调用者。
在主程序中,调用shell()函数并将输出打印出来。
请注意,subprocess.run()函数是Python 3.5及以上版本中引入的,如果使用Python 3.4或更低版本,可以使用subprocess.check_output()函数来达到相同的效果。具体使用方法可以参考Python官方文档中subprocess模块的相关说明。