代码如下
import subprocess
def execute_command(command):
try:
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
returncode = 0
except subprocess.CalledProcessError as e:
output = e.output
returncode = e.returncode
return output.decode('utf-8', 'ignore'), returncode
此代码同样可以在PyQt5内使用
这个示例代码定义了一个名为 execute_command
的函数,它接受一个字符串类型的参数 command
表示要执行的命令,返回一个元组 (output, returncode)
,其中 output
表示命令输出结果字符串,returncode
表示命令返回值。
本代码使用了 Python 标准库中的 subprocess
模块来执行命令和读取输出结果。我们通过调用 subprocess.check_output()
方法来执行传入的命令,并指定 shell=True
来启动 shell 进程执行命令。如果命令执行成功,该方法会返回命令输出结果的字节串;否则会抛出一个 CalledProcessError
异常,其中包含命令输出结果和返回值。最后,我们将输出结果转换成字符串类型并返回。