I have the following code which gets data from a webscrape.
I only just learnt how to use the
subprocess.Popen
and i am trying to ouse my initiative along with other answers to similar questions on how to use the
subprocess.Popen
to execute the script below to get the webscrape data into my insert field updated every 30 seconds or so. But it is not working. Please could you point me in the right direction?
import xlrd
import subprocess
from Tkinter import *
import urllib2
from ttk import *
import Tkinter as tk
class Application(Frame):
"""GUI to display results of 'equity get'"""
def __init__(self, master):
"""initialise the Frame"""
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create button, text and entry Widget"""
"""what it is i.e. label"""
url = "https://......."
request= urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<.......">", 1);
splitted_page = splitted_page24[1].split("</.......>", 1)
self.data = Label(self, text ="Data")
self.data1 = Entry(self, width = 10)
self.data1.insert(0,splitted_page[0])
self.data.grid(column = 1, row = 1)
self.data1.grid(column = 2, row = 1)
self.data1.grid(column = 3, row = 1)
a = 0
while a < 10:
a += 1
time.sleep(15)
while True:
out = subprocess.Popen(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
app = Application(root)
root.title("reload test")
root.geometry("700x300")
root.mainloop()
the error i get is
error no 22: invalid syntax referring to the script between the
(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
then multiple command line windows open displaying the same error and i have to shut down the computer to stop it!
i amended the reference to my file with the 'r' prefix as follows:
([r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
but removed the python.exe call as it just calling up the command line window. Now, i receive the following error message:
Traceback (most recent call last):
File "C:\Users\....\Desktop\Py\Python27\.....\tester.py", line 46, in <module>
app = Application(root)
File "C:\Users\......\Desktop\Py\Python27\.....\tester.py", line 18, in __init__
self.create_widgets()
File "C:\Users\.....\Desktop\Py\Python27\......\tester.py", line 44, in create_widgets
out = subprocess.Popen([r"C:\Users\Isaac\Desktop\Py\Python27\.....\tester.py"])
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 672, in __init__
errread, errwrite)
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 882, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
Python uses backslash to quote characters, like \n = newline and \t = tab.
Use an r prefix to make a raw string literal, like a Windows file path:
out = subprocess.Popen([r"C:\Users\.....\Desktop\Py\python.exe", r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
Related
Ok so the problem is : When I click on the upload button and I don't specify a file during the askopenfilename and I leave directly with the cross an error occurs 'playsound exception' that I didn't manage to catch with try/except statement otherwise I don't know how to prevent this or fix the problem ...
code :
from tkinter import *
from tkinter import ttk
from playsound import playsound
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('800x600')
frame1 = Frame(root,width='100',height='50',bg='black',borderwidth=1)
subframe1 = Frame(root, bg='black', width='660', height='351')
labelframe1 = Label(frame1,text='go to frame1',fg='orange',bg='black')
frame2 = Frame(root,width='100',height='50',bg='blue')
subframe2 = Frame(root, bg='blue', width='660', height='351')
labelframe2 = Label(frame2,text='go to frame2',fg='orange',bg='blue')
buttonframe1 = Button(subframe1, text="firstbutton",fg='orange')
entryframe1 = Entry(subframe1)
comboframe1 = ttk.Combobox(subframe1,values=['option1','option2' ,'option3'])
comboframe1.set('default option')
buttonframe2 = Button(subframe2, text="secondbutton",fg='orange')
entryframe2 = Entry(subframe2)
comboframe2 = ttk.Combobox(subframe2,values=['option1','option2' ,'option3'])
comboframe2.set('default option')
uploadbutton = Button(root,text='upload',fg='orange')
frame1.place(x=0,y=0)
labelframe1.place(relx=0.5,rely=0.5,anchor=CENTER)
frame2.place(x=0,y=140)
labelframe2.place(relx=0.5,rely=0.5,anchor=CENTER)
uploadbutton.place(x=0,y=240)
def change_frame1(*args):
subframe1.pack(side=RIGHT)
subframe2.pack_forget()
buttonframe1.place(x=0,y=0)
entryframe1.place(x=0,y=40)
comboframe1.place(x=0,y=80)
def change_frame2(*args):
subframe2.pack(side=RIGHT)
subframe1.pack_forget()
buttonframe2.place(x=0,y=0)
entryframe2.place(x=0,y=40)
comboframe2.place(x=0,y=80)
def upload(*args):
file = askopenfilename(filetypes= [('MP3 Files', '*.mp3')])
if file is not None:
playsound(file)
frame1.bind('<Button-1>', change_frame1)
labelframe1.bind('<Button-1>', change_frame1)
frame2.bind('<Button-1>', change_frame2)
labelframe2.bind('<Button-1>', change_frame2)
uploadbutton.bind('<Button-1>',upload)
root.mainloop()
Error :
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\user\project\pythonproject\venv\Lib\site-packages\project.py", line 327, in <lambda>
soundbutton = Button(root, text="upload",
command = lambda : upload())
File "C:\Users\user\project\pythonproject\venv\Lib\site-packages\project.py", line 341, in upload
playsound(file)
File "C:\Users\user\project\pythonproject\venv\Lib\site-packages\playsound.py", line 35, in _playsoundWin
winCommand('open "' + sound + '" alias', alias)
File "C:\Users\user\project\pythonproject\venv\Lib\site-packages\playsound.py", line 31, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 292 for command:
open "" alias playsound_0.39688356388365387
The specified command requires an alias, file, driver, or device name. Please supply one.
I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Hunter\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "c:\Users\Hunter\Documents\Programming\Python Scripts\Scripts\spoolClient\menuScript.py", line 46, in <lambda>
updateJsonButton = Button(preferences, text="Save Preferences", command=lambda: updateJson())
File "c:\Users\Hunter\Documents\Programming\Python Scripts\Scripts\spoolClient\menuScript.py", line 17, in updateJson
for i, j in zip(entryNames, entry):
File "C:\Users\Hunter\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1643, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str
When trying to run my script:
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from tkinter import filedialog
import qrMaker
import qrReader
import json
settings = {}
#define vars
preferencesSkippedRows = [1, 3, 5, 7, 9, 11]
def openPreferences():
def updateJson():
print("here")
for i, j in zip(entryNames, entry):
print("loopdie")
value = str(j.get())
settings[i]=value
settingsjson = json.dumps(settings)
print(settingsjson)
f = open("preferences.json","w")
f.write(settingsjson)
f.close()
preferences = Tk()
preferences.title("Preferences")
preferences.iconbitmap(qrMaker.getCurrentPath()+'icon.ico')
preferences.geometry('400x600')
topText = Label(preferences, width=30, text="Filament Spool Client Preferences")
cameraText = Label(preferences, width=30, text="Select Camera Instance:")
cameraEntry = Combobox(preferences, width=30, values=qrReader.getCameras())
qrWidthText = Label(preferences, width=30, text="QR Output Width (in.)")
qrWidthEntry = Entry(preferences, width=30)
qrHeightText = Label(preferences, width=30, text="QR Output Height (in.)")
qrHeightEntry = Entry(preferences, width=30)
text = [cameraText, qrWidthText, qrHeightText]
entry = [cameraEntry, qrWidthEntry, qrHeightEntry]
entryNames = ['cameraEntry', 'qrWidthEntry', 'qrHeightEntry']
updateJsonButton = Button(preferences, text="Save Preferences", command=lambda: updateJson())
for i in preferencesSkippedRows:
preferences.grid_rowconfigure(i, minsize=10)
topText.grid(column = 0, row = 0)
row=2
for text, entry in zip(text, entry):
text.grid(column = 0, row = row)
entry.grid(column = 1, row = row)
row+=2
updateJsonButton.grid(column=1, row=row+2)
preferences.mainloop()
openPreferences() #I call script.openPreferences() in my main program but I left this here for debugging purposes
I can see from the error message that the error occurs somewhere in the line that my zip function occurs, but I have no idea what causes this. Oddly enough, this error goes away if instead of setting updateJson equal to the command value of my Tkinter button state, I set updateJson, which calls the function right as the button object is initialized. I also know what the error is saying, I just don't know where an integer is coming from, and how I can fix this issue. Any help would be appreciated.
Update: I've just found that the actual zipping of the two lists is not the problem, but when I introduce the for loop, the same error occurs.
Answering to close out this thread, answer from "user2357112 supports Monica".
The issue in this script is that for text, entry in zip(text, entry) literally uses "entry" in the for loop, and is executed after the button instance is created, meaning that if updateJson is called during the button object initialization, then there will be no error thrown as entry is still defined as a list. However, after for text, entry in zip(text, entry) executes at startup, entry is now defined as the last object in the list entry, no longer the list entry itself. When the user presses the button and updateJson is called, an error is thrown as entry is not a list anymore(I'm not 100% sure on the error part).
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 3 years ago.
I use Python 2.7.15 and I am trying to create a GUI that will let you tweet with a custom source label ("Twitter for ...") but my current code while accepting the variable for the source label it does not like the status as a variable.
Code:
import tweepy
from Tkinter import *
auth = tweepy.OAuthHandler('lol', 'nice')
auth.set_access_token('try', 'xD')
api = tweepy.API(auth)
def tweet():
message = messageStorage.get()
sourceLabel = sourceLabelStorage.get()
api.update_status(message, source = sourceLabel)
gui = Tk()
gui.title('')
messageStorage = StringVar()
sourceLabelStorage = StringVar()
label0 = Label(gui, text='Enter Tweet').pack()
entry0 = Entry(gui, textvariable=messageStorage).pack()
label1 = Label(gui, text='Enter Source Label').pack()
entry1 = Entry(gui, textvariable=sourceLabelStorage).pack()
button0 = Button(gui, text='Tweet', command=tweet(), bg='#1da1f2').pack(pady=5)
gui.mainloop()
Error:
Traceback (most recent call last):
File "C:/Users/My Name/Desktop/customSourceLabel_twitter.py", line 24, in <module>
button0 = Button(gui, text='Tweet', command=tweet(), bg='#1da1f2').pack(pady=5)
File "C:/Users/My Name/Desktop/customSourceLabel_twitter.py", line 12, in tweet
api.update_status(message, source = sourceLabel)
File "C:\Python27\lib\site-packages\tweepy\api.py", line 195, in update_status
)(post_data=post_data, *args, **kwargs)
File "C:\Python27\lib\site-packages\tweepy\binder.py", line 250, in _call
return method.execute()
File "C:\Python27\lib\site-packages\tweepy\binder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
TweepError: [{u'message': u'Missing required parameter: status.', u'code': 170}]
Thanks in advance
From the Tweepy documentation, it looks as if you must explicitly identify that first parameter as status, like so:
api.update_status(status=message, source=sourceLabel)
EDIT: As #Bryan Oakley points out, there is also another bug in your code--in your call to Button(), the parameter command=tweet shouldn't have parentheses after the function name--but that's separate from and in addition to the error message you've posted.
I am very new in python cffi. I have to access my temprature module by using its Index or with its channel name. I am trying with both as you can see in my QmixTC class. I am getting attribute error. In other class, there is no errors. Can someone help me understand where is the problem. I am putting my code as well as error trace. Thanks.
main code with name qmix.py (importing it in to sample code):
class QmixTC (object):
"""
"""
def __init__(self, index=0, handle=None,name=''):
self.dll_dir = DLL_DIR
self.dll_file = os.path.join(self.dll_dir,
'labbCAN_Controller_API.dll')
self._ffi = FFI()
self._ffi.cdef(CONTROLLER_HEADER)
self._dll = self._ffi.dlopen(self.dll_file)
self._handle = self._ffi.new('dev_hdl *', 0)
if handle is None:
self.index = index
self._handle = self._ffi.new('dev_hdl *', 0)
self._call('LCC_GetChannelHandle', self.index, self._handle)
else:
self.index = None
self._handle = handle
self._ch_name="QmixTC_1_DO0_INA"
self._channel = self._ch_name + str(index)
self._call('LCC_LookupChanByName',
bytes(self._channel,'utf8'),
self._handle)
self.name = name
def _call(self, func_name, *args):
func = getattr(self._dll, func_name)
r = func(*args)
r = CHK(r, func_name, *args)
return r
def Setpoint_write (self, setpoint):
"""
Write setpoint value to controller device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[in] fSetPointValue The setpoint value to write
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_WriteSetPoint', self._handle[0], setpoint)
def enable_controllLoop (self, enable):
"""
Enables / disables a control loop.
If the control loop is enabled, then the output value is calculated periodically.
Parameters
ChanHdl Valid handle of a controller channel
Enable 1 = enable, 0 = disable
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_EnableControlLoop', self._handle[0], enable)
def read_temp_value (self, actualvalue):
"""
Read actual value from device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[out] pfActualValue Returns the actual controller value
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_ReadActualValue', self._handle[0], actualvalue)
if __name__ == '__main__':
import os.path as op
dll_dir = op.normpath('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = op.normpath('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_Pump\\Configurations\\QmixTC_pump')
bus = QmixBus(config_dir=config_dir)
bus.open()
bus.start()
controller_0 = QmixTC(index=0)
controller_0.enable_controllLoop(1)
sample program:
from __future__ import division, print_function
from win32api import GetSystemMetrics
import numpy as np
import os
import qmix
import pandas as pd
#%% CHANNEL INITIALIZATION
if __name__ == '__main__':
dll_dir = ('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = ('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_test1\\Configurations\\QmixTC_test1')
qmix_bus = qmix.QmixBus(config_dir=config_dir,dll_dir=dll_dir)
qmix_bus.open()
qmix_bus.start()
controller_0 = qmix.QmixTC(index=0)
controller_0.Setpoint_write(50)
error:
Traceback (most recent call last):
File "<ipython-input-5-40d4a3db9493>", line 17, in <module>
controller_0 = qmix.QmixTC(index=0)
File "qmix.py", line 921, in __init__
self._call('LCC_GetChannelHandle', self.index, self._handle)
File "qmix.py", line 937, in _call
func = getattr(self._dll, func_name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 875, in __getattr__
make_accessor(name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 870, in make_accessor
raise AttributeError(name)
AttributeError: LCC_GetChannelHandle
I'm new to Pythong and I have been trying to get a button within UltimateListCtrl. I still can't figure out what I'm doing wrong. Here is my code:
try:
from agw import ultimatelistctrl as ULC
except ImportError: # if it's not there locally, try the wxPython lib.
from wx.lib.agw import ultimatelistctrl as ULC
self.table = ULC.UltimateListCtrl(self, -1, agwStyle=ULC.ULC_REPORT|
ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)
self.table.InsertColumn(0, "Name")
self.table.InsertColumn(1, "Size")
self.table.InsertColumn(2, "Download")
for i in range(0, len(masterlist)):
pos = self.table.InsertStringItem(i,str(masterlist[i]['name']))
self.table.SetStringItem(pos, 1,str(masterlist[i]['size']))
button = wx.Button(self, id=i, label="Download")
self.table.SetItemWindow(pos, col=2, wnd=button, expand=True)
masterlist is a list of download items.
I get this traceback:
Traceback (most recent call last):
File "E:\TestApp.py", line 67, in Display
self.table.SetItemWindow(pos, col=5, wnd=button, expand=True)
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\lib\agw\ultimatelistctrl.py", line 12961, in SetItemWindow
return self._mainWin.SetItemWindow(item, wnd, expand)
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\lib\agw\ultimatelistctrl.py", line 9021, in SetItemWindow
item.SetWindow(wnd, expand)
File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\lib\agw\ultimatelistctrl.py", line 1863, in SetWindow
mainWin = listCtrl._mainWin
AttributeError: 'MainWindow' object has no attribute '_mainWin'
button's parent should be your ULC i.e self.table
So change this line:
button = wx.Button(self, id=wx.ID_ANY, label="Download")
to this:
button = wx.Button(self.table, id=wx.ID_ANY, label="Download")
Update in response to comment:
For some reason it doesn't seem to be possible to delete all items in a ULC with the
DeleteAllItems() method if any of the items contain widgets so instead use DeleteItem().
def emptyList(self)
itemCount = self.list.GetItemCount()
for item in xrange(itemCount):
self.list.DeleteItem(0)