我打算创建一个需要Linux终端上执行一些命令的GUI。我怎样才能在Tkinter的GUI按钮执行Linux终端命令?
你需要运行一个按钮被点击时,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
要执行的命令,使用一种叫做子的Python模块。该代码如下:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)