上的Tkinter运行Linux终端的命令

问题描述 投票:-2回答:2

我打算创建一个需要Linux终端上执行一些命令的GUI。我怎样才能在Tkinter的GUI按钮执行Linux终端命令?

python user-interface ubuntu tkinter terminal
2个回答
1
投票

你需要运行一个按钮被点击时,Linux命令的功能。

为此,Python的内置库subprocess就足够了。的语法,以运行在终端中的简单ls -l如下:

subprocess.run(["ls", "-l"])

对于使用的样本tkinter程序,你必须包裹subprocess.run()的功能。例如:

from tkinter import *
import subprocess

def run():
    subprocess.run(["ls", "-l"])

root = Tk()
Button(root, text="Click to run 'ls -l'", command=run).pack()
root.mainloop()

要了解更多关于subprocess模块以及如何从终端捕获输出:https://docs.python.org/3/library/subprocess.html


0
投票

要执行的命令,使用一种叫做子的Python模块。该代码如下:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
© www.soinside.com 2019 - 2024. All rights reserved.