I have a function that opens up a webdriver session and then calls for external functions based on the input url.
from externalfunctions import *
def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
'a': a,
'b': b,
'c': c
}
if name in options:
ff = webdriver.Firefox()
ff.get(url)
result = options[name]()
ff.quit()
print(result)
return result
functions a,b,c are in externalfuntions.py
def a():
x = ff.find_element_by_css_selector('body')
return x
def b():
x = ff.find_element_by_css_selector('span')
return x
def c():
x = ff.find_element_by_css_selector('html')
return x
When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.
How do I do this without having to start a webdriver session every time the a,b,c functions are run.
This is basic Python (indeed, basic programming). If a function needs access to something, you need to pass it:
result = options[name](ff)
and
def a(ff):
x = ff.find_element_by_css_selector('body')
return x
etc.
You need to import the webdriver library (selenium) and declare the webdriver:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("window-size=1,1")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\XXX\chromedriver')
and then you can use:
driver.get(url)
driver.find_element_by_css_selector('html')
Related
I think my question was not very clear before..
I'm trying to create a class module that includes a function does a mutiprocessing of a ctpyes function.
I'm re-posting a working small code.
All I want to do is to remove the code below and call the function directly from my class. But it seems very hard since ctypes object is not picklable.. Is there a way to resolve this issue? Even a small hint will be appreciated!! Will I have to switch to using cython instead of ctypes? will that even help?
def myc(x):
return a.funct(x)
Below is the working code.
from ctypes import *
from ctypes.util import find_library
import multiprocess as mp
class ctest():
def __init__(self):
self.libapr = cdll.LoadLibrary(find_library('apr-1'))
self.libapr.apr_fnmatch.argtypes = [c_char_p, c_char_p, c_int]
self.libapr.apr_fnmatch.restype = c_int
def funct(self,x):
y=self.libapr.apr_fnmatch(x, 'name.ext', 0)
return y
def mymult(self,func,xlist):
pool=mp.Pool(20)
res=pool.map(func,xlist)
pool.close()
return res
if __name__ == "__main__":
a=ctest()
def myc(x):return a.funct(x)
print a.mymult(myc,['*.txt','*.ext'])
Below is what I want to do.
from ctypes import *
from ctypes.util import find_library
import multiprocess as mp
class ctest():
def __init__(self):
self.libapr = cdll.LoadLibrary(find_library('apr-1'))
self.libapr.apr_fnmatch.argtypes = [c_char_p, c_char_p, c_int]
self.libapr.apr_fnmatch.restype = c_int
def funct(self,x):
y=self.libapr.apr_fnmatch(x, 'name.ext', 0)
return y
def mymult(self,func,xlist):
pool=mp.Pool(20)
res=pool.map(func,xlist)
pool.close()
return res
if __name__ == "__main__":
a=ctest()
a.mymult(a.funct,['*.txt','*.ext'])
I just ran into some strange behavior that has me stumped. I'm writing a simple little GUI for some in-house data processing. I want to allow a user to switch between a few different data-processing modes and input some parameters which define how the data is processed for each mode. The problem is that when the user inputs new parameters, the app ignores requests to switch modes.
The code below replicates the issue. I apologize for the size, this was the shortest code that replicates the problem.
import Tkinter as Tk
class foo(Tk.Frame):
def __init__(self):
self.master = master =Tk.Tk()
Tk.Frame.__init__(self,self.master) #Bootstrap
#Here mode and parameters as key, value pairs
self.data = {'a':'Yay',
'b':'Boo'
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,
text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,
text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#This is how I'm retrieving the user selected parameters
#property
def innerdata(self):
return self.data[self.sv.get()]
#And how I'm setting the user defined parameters
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
app = foo()
app.mainloop()
Expected behavior:
1) Press button 'a' then 'print' prints:
Yay
2) Press button 'b' then 'print' prints:
Boo
3) Type 'Zep Rocks' into the entry field and press apply
4) Pressing 'print' now yields
Zep Rocks
5) Pressing 'a' then 'print' should yield
Yay
But instead yields
Zep Rocks
Which might be true, but not desired right now. What is going on here?
Edit: I have some new information. Tk.Frame in python 2.7 is not a new-style class. It isn't friendly with descriptors, so rather than interpreting the '=' as a request to use the foo.innerdata's __set__ method, it just assigns the result of self.e.get() to innerdata.
ARGLEBARGLE!!!
Still an open question: how do I get this to do what I want in a clean manner?
So the core problem is that Tk.Frame doesn't subclass from object, so it is not a new-style python class. Which means it doesn't get down with descriptors like I was trying to use. One solution that I found is to subclass my app from object instead.
Code that solves my problem is below:
import Tkinter as Tk
class foo(object):
def __init__(self,master):
self.master = master #Bootstrap
self.mainloop = master.mainloop
self.data = {'a':{'value':7,'metavalue':False},
'b':{'value':'Beeswax','metavalue':True}
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#property
def innerdata(self):
return self.data[self.sv.get()]
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
master = Tk.Tk()
app = foo(master)
app.mainloop()
I have the code:
import time
import numpy as np
from scipy.optimize import fmin_tnc
from enthought.traits.api import *
from enthought.traits.ui.api import *
class Minimizer(HasTraits):
iteration = Int(0)
run = Button
def callback(self, x):
self.iteration += 1
print self.iteration
time.sleep(0.5)
def func(self, x):
return (x**2).sum()
def fprime(self, x):
return 2*x
def minimize(self):
x0 = np.random.rand(50)
fmin_tnc(self.func, x0, fprime=self.fprime, messages=0, callback = self.callback)
def _run_fired(self):
self.minimize()
traits_view = View(Item('iteration'), UItem('run'))
m = Minimizer()
m.configure_traits()
After running the above and pressing Run button i expected the 'iteration' attribute will be updated in the GUI at each iteration, but this is not the case. I suspect that this is because this value is changed by callback from C. What should be done to update the user interface in these circumstances?
Regards,
Marek
The call to m.configure_traits() is blocking, which means execution of your script will not continue past that line until you close the window created by that call. In other words, m.minimize does not get called while the window is open.
I found the solution. Simply, 'minimize' method have to be non-blocking, so implementing minimization in separate thread, like this:
def minimize(self):
x0 = np.random.rand(50)
#fmin_tnc(self.func, x0, fprime=self.fprime, messages=0, callback = self.callback)
import thread
thread.start_new_thread(fmin_tnc, (self.func, x0), {'fprime':self.fprime, 'messages':0, 'callback':self.callback})
will result in updating the UI at real-time...
Thanks,
Marek
I'am using Boneh-Lynn-Shacham Identity Based Signature scheme for my final year project for getting encryption keys
from charm.toolbox.pairinggroup import *
from charm.engine.util import *
debug = False
class IBSig():
def __init__(self, groupObj):
global group
group = groupObj
def dump(self, obj):
ser_a = serializeDict(obj, group)
return str(pickleObject(ser_a))
def keygen(self, secparam=None):
g, x = group.random(G2), group.random()
g_x = g ** x
pk = { 'g^x':g_x, 'g':g, 'identity':str(g_x), 'secparam':secparam }
sk = { 'x':x }
return (pk, sk)
def sign(self, x, message):
M = self.dump(message)
if debug: print("Message => '%s'" % M)
return group.hash(M, G1) ** x
def verify(self, pk, sig, message):
M = self.dump(message)
h = group.hash(M, G1)
if pair(sig, pk['g']) == pair(h, pk['g^x']):
return True
return False
def main():
groupObj = PairingGroup('../param/d224.param')
m = { 'a':"hello world!!!" , 'b':"test message" }
bls = IBSig(groupObj)
(pk, sk) = bls.keygen(0)
sig = bls.sign(sk['x'], m)
if debug: print("Message: '%s'" % m)
if debug: print("Signature: '%s'" % sig)
assert bls.verify(pk, sig, m)
if debug: print('SUCCESS!!!')
if __name__ == "__main__":
debug = True
main()
when I am implementing it in python the code was not able to find the module named pairing though I have added Charm module to my library.Getting error like
Traceback (most recent call last):
File "C:\Users\Sailesh\Desktop\bls.py", line 1, in <module>
from charm.toolbox.pairinggroup import *
File "C:\Python27\lib\charm\toolbox\pairinggroup.py", line 2, in <module>
from charm.core.math.pairing import serialize
ImportError: DLL load failed: The specified module could not be found.
I have taken the code from
Boneh-Lynn-Shacham Identity Based Signature code and downloaded the module charm from charm module link. Let me know where is the error or whether the
problem is with the module. I cant figure out what is the problem. Thanks in advance.
Try the 0.43 version directly fron github:
https://github.com/JHUISI/charm/releases
I am trying to invoke a method from combo box selected change event
with lambda expression but I am stuck with following error
TypeError: () takes no arguments (1 given)
I think I have passed 1 argument as per the method definition, could somebody please help me where I am wrong
or any other combobox selected change event code will be great help!
please note my code
self.boxWidget[boxName].bind("<<ComboboxSelected>>", lambda:invoke_Setting_Group(self))
def invoke_My_method1(self):
print "expand another window"
I am trying to pass the first class object to the second python script file for variable value assigning easeness.I tried to use this combox event change code without lambda then I noticed that this method is getting called automatically so I used lambda to prevent this automatic method calling
Sorry I am not having the knowledge on lambda expression usage; here I used only to prevent the automatic method execution. Without lambda expression I noticed my combo box function starts automatically, I did not understand why it happens so?
I am using TKinter python 2.6
More Detailed Code of above:
#Main_GUI_Class.py
##----------------------
import sys
class App():
def __init__ (self,master,geometry=None,root=None):
try:
self.master=master
if not root:
self.root=Tkinter.Toplevel(master)
def initUI(self):
try:
self.master.title("GUI")
menubar = Menu(self.master)
self.root.config(menu=menubar)
fileMenu.add_command(label='Open')
submenu_ncss.add_command(label='Model Setting',command=lambda:Combo_Expand_Script.Call_Model_Setting(self))
##----------------------
def main():
r = Tkinter.Tk()
r.withdraw()
r.title("GUI Sample")
r.wm_iconbitmap(Pic1)
v = App(r)
r.mainloop()
if __name__ == "__main__":
main()
##Combo_Expand_Script.py
##-----------------------
import sys
import Tkinter
import Main_GUI_Class
def Call_Model_Setting(self):
try:
self.PopUpWin = Toplevel(bg='#54596d',height=500, width=365)
self.PopUpWin.title("POP UP SETTING")
#Combo Boxs in Pop Up
boxNameGroup="boxSetting"
boxPlaceY=0
for Y in range(4):
boxName=boxNameGroup+str(Y)
if Y == 0:
boxPlaceY=50
else:
boxPlaceY=boxPlaceY+40
self.box_value = StringVar()
self.boxWidget[boxName] = ttk.Combobox(self.PopUpWin, height=1, width=20)
if Y== 0:
self.boxWidget[boxName]['values'] = ('A', 'B')
self.boxWidget[boxName].current(1)
if Y== 1:
self.boxWidget[boxName]['values'] = ('X', 'Y')
self.boxWidget[boxName].bind("<<ComboboxSelected>>",lambda:invoke_Setting_Group(self))
self.boxWidget[boxName].place(x=180, y = boxPlaceY)
#Buttons in Pop Up
self.btnApply = tk.Button(self.PopUpWin,width=10, height=1,text="Apply",relief=FLAT,bg=btn_Bg_Color,command=lambda: treeDataTransfer(self,0))
self.btnApply.pack()
self.btnApply.place(x=75, y = 460)
self.btnCancel = tk.Button(self.PopUpWin,width=10, height=1,text="Cancel",relief=FLAT,command=lambda: deleteTreeNodes(self))
self.btnCancel.pack()
self.btnCancel.place(x=170, y = 460)
except IOError:
print "Error: data error"
def invoke_Setting_Group(self):#, event=None
try:
#self.boxName.current(0)
self.boxWidget["boxSetting3"].current(0)
self.PopUpWin['width']=1050
self.PopUpWin['height']=700
self.btnApply.place(x=500, y = 550)
self.btnCancel.place(x=600, y = 550)
self.txtWidget={}
lsttxtSetting = ['1', '2','3 ','4','5 ','6','7','8','9','10']
for t in range(10):
txtName=txtNameGroupTS+str(t)
if t == 0:
txtPlaceY=120
else:
txtPlaceY=txtPlaceY+30
self.txtWidget[txtName] = Text(self.groupSettingFrame,height=1, width=10,borderwidth = 2)
self.txtWidget[txtName].insert(INSERT, lsttxtSetting[t])
self.txtWidget[txtName].pack()
self.txtWidget[txtName].place(x=200, y = txtPlaceY)
except IOError:
print "Error: Group Settings Popup error"
def turbDataTransferBind(self):
for P in range(0,3):
boxName="boxSetting"+str(X)
dataSettingbox=self.lstTurb[X]+" "+self.boxWidget[boxName].get()
self.root_node_Setting = self.tree.insert( self.root_node_ChildSetting["ChildSettingNode"], 'end', text=dataSettingbox, open=True)
def treeDataTransfer(self,dlgTurbFlag):
self.treeDataTransferBind()
print "data tranfer sucess"
def deleteTreeNodes(self):
print "delete nodes"
command= and bind expect function name - without () and arguments - so in place of
If you use
.bind("<<ComboboxSelected>>", invoke_Setting_Group(self) )
then you use result from invoke_Setting_Group(self) as second argument in .bind(). This way you could dynamicly generate function used as argument in bind
TypeError: () takes no arguments (1 given)
This means you have function function() but python run it as function(arg1)
You run lambda:invoke_Setting_Group(self) but python expects lambda arg1:self.invoke_Setting_Group(self)
You could create function with extra argument
def invoke_My_method1(self, event):
print "expand another window"
print "event:", event, event.widget, event.x, event.y
And then you could use it
.bind("<<ComboboxSelected>>", lambda event:invoke_Setting_Group(self, event))
BTW: it looks strange - you have class App() but in second file you use only functions instead of some class too.