Python console prints output differently than sypder console - python

I have a python code that takes measurements off of a HP LCR Meter and collects the data for us in various ways. I recently created a GUI for imputing initial conditions for employees not comfortable modifying variables in the code. Everything works except for 1 thing. WE use the latest python xy so python version 2.6.6 with pyqt and spyder on a windows 7 PC.
Normally we would open the code in spyder. But opening spyder takes a while and my supervisor liked the ability to just double click on the file which opens the GUI with a python console window to print errors and various information as you would see in spyder.
As can be seen in the screen shots provided, there is a initial machine setup mode for setting up the device to be scanned by the LCR Meter and there are two user inputs that the code prompts. On spyder it prints these prompts nicely in the console but in the python console opened without spyder it continuously prints QCoreApplication::exec: The event loop is already running Weird thing is you can still just push enter twice as normal and the code will run like normal. But its going to be confusing to basically everyone but me.
Does anyone know why this would be happening?
Here are the pictures of the output
Here is the code that prompts the input.
lcr = visa.instrument('GPIB::17')
#clear the instrument
lcr.write('*RST;*CLS')
#enable operation complete notification
lcr.write('*OPC')
if parallel:
lcr.write('FUNC:IMP CPG') #Parallel capacitance, conductance model
else:
lcr.write('FUNC:IMP CSRS') #Series capacitance, resistance model
lcr.write('APER '+integration+','+averages)
lcr.write('OUTP:HPOW ON')
lcr.write('OUTP:DC:ISOL OFF')
lcr.write('VOLT '+vac)
lcr.write('TRIG:SOUR BUS')
if zero == True:
#set open correction parameters
lcr.write('DISP:PAGE CSET')
lcr.write('CORR:LENG 1')
lcr.write('CORR:METH SING')
lcr.write('CORR:LOAD CPG')
lcr.write('CORR:USE 10')
lcr.write('CORR:SPOT1:STATE ON')
lcr.write('CORR:SPOT2:STATE OFF')
lcr.write('CORR:SPOT3:STATE OFF')
lcr.write('CORR:SPOT1:FREQ '+frequency)
#perform open correction -> unprobe device\
raw_input('Unprobe DUT and press ENTER to continue...')
lcr.write('CORR:SPOT1:OPEN')
lcr.write('CORR:OPEN:STATE ON')
lcr.write('DISP:PAGE MEAS')
#poll lcr to determine measurment state
lcr.write('*OPC?')
done = lcr.read()
while done == 0:
lcr.write('*OPC?')
done = lcr.read()
time.sleep(0.5)
#reprobe device
raw_input('Probe DUT, then press ENTER')
lcr.write('FREQ '+frequency)
The Prompts are the two raw_input().

Reason why you get continuous messages in your console, is that system logs use same output-stream than your app.
Spyder is nice program, which just embeds IPython or Python(backup) console in QT window, you can use similar solution - just use Qt4 to draw window, which includes IPython console
What you need to do is this(source):
def embed_ipython(window):
"wrapper funcs - works < IPython 0.11"
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(user_ns = dict(w = window))
ipshell()
Here ‘window’ is a central object of some kind that you want to expose to IPython (to manipulate, test various methods, etc).
GUI app initialization would be like this:
if __name__ == "__main__":
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.show()
embed_ipython(window)
sys.exit(app.exec_())
Some additional readings:
QT4 tutorial: http://zetcode.com/tutorials/pyqt4/firstprograms/
Similar topic - how to embed python console: How to embed a Python interpreter in a PyQT widget
IPython and QT console: http://ipython.org/ipython-doc/dev/interactive/qtconsole.html

Related

Displaying other files of the same directory in a file in Python

I am creating a piece of software for my organisation which I recently started, and I am using the Tkinter module in Python to create my software. I have created a word processor and an online encyclopaedia for the software.
The idea is that the main program is where you can access all the applications just by the click of a button - similar to how a desktop functions. I have created the main function that will open the applications, but when you run the program, it opens the application first and then the main program where you access the application. Everything is working fine, and there are no error messages which show up when I run the program.
I've tried researching any solutions to my problem, but they don't give me anything that I can do to fix my problem. How I have structured my function for opening the applications is that I have created a function for each application and in the Button() function, that function for the application will be the command.
Here is the code for the software that I am developing:
from tkinter import *
import time
import os
import Wordee as wordee
window = Tk()
window.title("Brainwave One")
window.iconbitmap('Brainwave-One.ico')
def get_datetime():
timeVariable = time.strftime("%I:%M %p, %A %d %B %Y")
date_time.config(text=timeVariable)
date_time.after(200,get_datetime)
def wordee():
print(wordee)
wordee = Button(window,text="Wordee",font=("Calibri",23),command=wordee)
wordee.place(relx=0.25,rely=0.1875,anchor="center")
date_time = Label(window,font=("Calibri",15))
date_time.grid(row=0,column=0)
title = Label(window,text="Brainwave One",font=("Calibri",40))
title.place(relx=0.5,rely=0.05,anchor="center")
title = Label(window,text="From The Brainwave Incorporation",font=("Calibri",13))
title.place(relx=0.5,rely=0.083,anchor="center")
get_datetime()
window.mainloop()

How do I open a minimized window using python?

is it possible to un-minimize a minimized window using python on windows 10? (I'm using python 3.8)
I would add more detail but that's really all I need to say.
I combined information from multiple sources and got this to work (Miniconda Python 3.6, Windows 10)
import win32gui
import win32con
def windowEnumHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
def bringToFront(window_name):
top_windows = []
win32gui.EnumWindows(windowEnumHandler, top_windows)
for i in top_windows:
# print(i[1])
if window_name.lower() in i[1].lower():
# print("found", window_name)
win32gui.ShowWindow(i[0], win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(i[0])
break
# Test with notepad
if __name__ == "__main__":
winname = "notepad"
bringToFront(winname)
The Handler is not optimal; it spits out various processes that are not the windows in the taskbar. However, as long as your window_name is specific I don't think you'll run into problems. If you remove the break, all matches will be "opened".
Sources: Mouse and Python Blog
Another StackOverflow question

GUI Interface For Command Line Input/Output

I was hoping somebody could point me in the right direction for a project I would like to do. My intention is simple, to have a GUI that allows a user to input a string, that string fills into a pre-determined line of command line text, runs through the command line and returns what is printed on the command line screen. I've been leaning toward using Python for this but I am still not sure about the syntax that will accomplish even the first part, where a user will input a string and that string will run through the line of command line text. Any sort of input would be greatly appreciated!
This is a simple GUI using tkinter for python
try:
import tkinter as tk # python v3
except:
import Tkinter as tk # python v2
# This function is called when the submit button is clicked
def submit_callback(input_entry):
print("User entered : " + input_entry.get())
return None
####################### GUI ###########################
root = tk.Tk()
root.geometry('300x150') #Set window size
# Heading
heading = tk.Label(root, text="A simple GUI")
heading.place(x = 100, y = 0)
input_label = tk.Label(root, text="Enter some text")
input_label.place(x = 0, y = 50)
input_entry = tk.Entry(root)
input_entry.place(x = 100, y = 50)
submit_button = tk.Button(root, text = "Submit", command = lambda: submit_callback(input_entry))
submit_button.place(x = 200, y = 90)
root.mainloop()
#############################################################
Developing a GUI is a big project for python beginners, there are several possibilities to do this. If you want to seriously develop GUI applications in Python I would recommend you to try Qt4 or Qt5 via pyside or pyqt. You may need one or more tutorials and maybe some problems to get your first working GUI applications, but you will be able to build any kind of professional cross-platform applications using this libraries.
With running command line text, you mean system commands or python commands? If you want to run system commands, I would recommend you to write a short python script, that handles user input (within the python commandline) and passes it to the system using subprocess (from subprocess import call).
If you have done your first simple textform in pyqt and the script that handles user input try to connect them by wrapping the Qt application around the commandline script. If you just looking for a quick and dirty solution there are several libraries, that support some easy to setup GUI frames or webinterfaces (to run in the browser on the local machine). But if you are a programming beginner I would highly recommend to split this into twor or three minor projects, to keep the frustration level low ;).
Edit Python2 vs Python3: pyqt and pyside are available for both python2 and python3 (as the most, but not all libraries) so your choice between py2 and py3 is on your own. The Syntax is almost the same (except the print() command), but the libraries you install are only working in the version you installed them.
If you are working on a linux machine you can easily install both versions in parallel if you want to make sure the right version is called you can specify the command such as python2 or python3 instead of running the default with python
Edit2 handle user input:
from subprocess import check_output
def predefined_command(user_input):
command = ['net', 'user', '/domain', user_input]
answer = check_output(command, args)
decoded = answer.decode('utf8')
return answer

wxPython - Showing logo while importing

I am running a wxPython application that does a lot of modules and packages importing at the beginning and gathering information about the computer (network interfaces, internet connection..) so it takes time, and I'm showing a logo in that time until it ends. the problem is that the logo crashes if you press on it (because the importing are on the MainThread and the GUI can't respond to events), How can I show a logo while importing without letting the GUI crash? (I don't want to let the user to click on the Logo anyway)
Inspired by Tim Roberts in this wxPython-users thread I first tried to spin off the splash screen in a separate thread, which did not work (wxwidgets complains it it not in the main thread). So I did the only obvious thing which I should have done in the first place: make the long running at startup a separate thread.
Side effect: As the splash screens now can react to events, it will disappear when clicked on.
import wx
class long_running(object):
def __init__(self):
bitmap = wx.EmptyBitmap(300, 150, 127)
self.mainframe = wx.Frame(None, -1, 'mainframe')
self.splash = wx.SplashScreen(bitmap, wx.SPLASH_TIMEOUT, 20000, self.mainframe)
def start(self):
import time
# mimicking something taking very long time on startup
for i in range(20):
time.sleep(0.5)
print i
wx.CallAfter(self.continue_)
def continue_(self):
#Destroy the splash screen.
if self.splash:
self.splash.Hide()
# self.splash.Destroy()
self.mainframe.Show()
if __name__ == '__main__':
import thread
app = wx.App()
long_rnn = long_running()
# Begin loading the application.
thread.start_new_thread(long_rnn.start, ())
# Application loaded.
app.MainLoop()
In a recent project (on Windows7 and wxPython 2.9.5.1): For displaying a wx.SplashScreen while modules are importing we did the following:
We have a main module, which does import wx in the beginning, create the wx.App and display the splash screen. Only after showing the splash screen we begin to import the "heavy" modules. The very first startup will take 40 seconds. In fact the app will crash if the user clicks on the splash screen. Better said, Windows displays a message box (EDIT2) with "Python.exe has stopped working." If the user clicks "Terminate" the app will in fact terminate/crash. If the user does nothing, the app will start up normally. So on Windows there is no "real" crash. It will also not happen when starting the second time (because things are cached)? On subsequent starts startup time is 5 seconds. Sorry, no real answer but too long for a comment also.
EDIT: Minimum working example added: Click every one or two seconds on the splash while it is displayed to make Windows show the "Python has stopped working" dialog. The dialog will simply go away when long_running() has returned.
# -*- coding: utf-8 -*-
def long_running():
import time
time.sleep(10)
# does not show "Python ... stopped working ..."
#for _ in range(20):
# time.sleep(0.5)
# wx.Yield()
if __name__ == '__main__':
import wx
app = wx.App()
bitmap = wx.EmptyBitmap(300, 150, 127)
splash = wx.SplashScreen(bitmap, wx.SPLASH_TIMEOUT, 20000, None)
# Begin loading the application.
long_running()
# Application loaded.
#Destroy the splash screen.
splash.Hide()
splash.Destroy()
app.MainLoop()

Different behaviour between python console and python script

I am experiencing different behaviour on the same code using the python console and a python script.
The code is as follows:
import gtk
import webkit
win = gtk.Window()
win.show()
web = webkit.WebView()
win.add(web)
web.show()
web.open("http://www.google.com")
When running the code in the python console, the output is a new frame that contains the google main page.
When running the code as a script, the result is a void frame. It closes very fast but even if I use a delay function, the webkit is not added to the frame.
How is it possible?
Furthermore, using PyDev IDE it flags: "unresolved import: gtk",
but if i run the project, the program starts without problem of compilation. is it normal?
Add
gtk.main()
to the end of your script. This starts the gtk event loop.
import gtk
import webkit
class App(object):
def __init__(self):
win = gtk.Window()
win.connect("destroy", self.destroy)
web = webkit.WebView()
web.open("http://www.google.com")
win.add(web)
web.show()
win.show()
def destroy(self, widget, data = None):
gtk.main_quit()
app = App()
gtk.main()
My guess is that the console keeps the python session open, while at the end of the script the program closes. When the script closes, it takes everything it created with it.
Something to test this theory: if you type "exit" in the console do you see the interface shut down in the same manner? If so, think of some code (e.g. a pause like a raw_input) that will allow the script to stay open.
Good luck!

Categories