在Python GUI中运行Shell脚本
我有一个图形用户界面(GUI),当按钮被按下时,它会执行一些功能。
现在我想在这个界面里创建一个按钮,点击后可以在后台运行一个脚本。
我该怎么做呢?
4 个回答
0
使用Tkinter来创建一个按钮。如果想了解更多信息,可以看看这个视频:http://www.youtube.com/watch?v=Qr60hWFyKHc
下面是一个例子:
from Tkinter import *
root = Tk()
app = Frame(root)
app.grid()
button1 = Button(app,"Shell Script")
button1.grid()
root.mainloop()
要添加功能,可以把button1那一行改成:
button1 = Button(app,"Shell Script",command=runShellScript)
def runShellScript():
import subprocess
subprocess.call(['./yourScript.sh'])
1
接着@lakesh说的内容,下面是完整的脚本:
import Tkinter
import subprocess
top = Tkinter.Tk()
def helloCallBack():
print "Below is the output from the shell script in terminal"
subprocess.call('./yourscript.sh', shell=True)
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
请注意,这个shell脚本和python脚本在同一个文件夹里。
如果需要的话,可以运行 chmod 777 yourscript.sh
来修改脚本的权限。
subprocess.call('./yourscript.sh', shell=True)
而且使用 import Tkinter
而不是 import tkinter
解决了我遇到的问题。
1
Python可以通过一个叫做subprocess的模块来运行shell脚本。如果你想让它在后台运行,可以从一个新的线程开始。
使用这个模块的方法如下:
import subprocess
...
subprocess.call(['./yourScript.sh'])
如果你想了解更多关于Python多线程的知识,可以看看这个链接:如何在Python中使用线程?
3
不太确定你的问题是关于如何在Python中调用一个shell脚本,还是如何在你的图形界面(GUI)中制作一个按钮。如果是前者,我上面的评论(推荐你去看看subprocess.Popen)就是解决办法。否则:
# assuming Python3
import tkinter as tk
import subprocess as sub
WINDOW_SIZE = "600x400"
root = tk.Tk()
root.geometry(WINDOW_SIZE)
tk.Button(root, text="Push me!", command=lambda: sub.call('path/to/script')).pack()