Executing system commands with wxpython

Paul McNett p at ulmcnett.com
Fri Sep 10 13:36:59 EDT 2004


twsnnva writes:

> Could anyone give me an example (code) of a simple program
> with a button that when clicked executes a linux shell or
> windows dos command like "ifconfig" or "ipconfig" and prints
> the output somewhere in the same window. Thanks.

Okay, I just re-read your subject and you specified wxPython 
there, but I already wrote up how to do it with Tkinter. The 
irony is that I'm way more comfortable with wxPython, and had 
to spend extra time looking up the Tkinter syntax. Anyway, I'm 
not sure if your question is more "how to execute system 
commands" or "how to display a button" so why don't you run 
with this code and see if it works for you. 

Hint: you'll use the same Python code to execute system commands 
- the ui toolkit doesn't matter.

# -- Begin sample code

import sys, os
import Tkinter

# Define the main root top-level window:
root = Tkinter.Tk()

# Define the button and edit area:
button = Tkinter.Button(root, text="IP Configuration")
edit = Tkinter.Text(root)

# Lay out the button and edit area:
button.pack()
edit.pack()

# Define the callback function for the button click:
def sysCommand(evt):
	if "linux" in sys.platform:
		file = os.popen("/sbin/ifconfig")
		result = file.read()
		file.close()
	elif "win" in sys.platform:
		file = os.popen("ipconfig")
		result = file.read()
		file.close()
	else:
		result = "Unsupported Platform: '%s'" % sys.platform
	edit.insert(Tkinter.END, result)
	

# Bind a click of the button to our callback function:
button.bind("<Button>", sysCommand)
button.bind("<space>", sysCommand)

Tkinter.mainloop()

#-- end sample code


-- 
Paul McNett
Independent Software Consultant
http://www.paulmcnett.com



More information about the Python-list mailing list