I am planning to create a GUI that needs to execute some commands on linux terminal. How can i execute Linux terminal commands on Tkinter GUI buttons?
You'll need a function that runs Linux commands when a button is clicked.
For this, Python's in-built library subprocess
is sufficient. The syntax is as follows in order to run a simple ls -l
in the terminal:
subprocess.run(["ls", "-l"])
For a sample tkinter
program with usage, you'll have to wrap the subprocess.run()
in a function. For example:
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()
To learn more about the subprocess
module and how to capture output from the terminal: https://docs.python.org/3/library/subprocess.html
To execute the commands, use a python module called subprocess . The code is as following:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.