Selenium + Xvfb concurrency issues - google-chrome

test.py
#!/usr/bin/env python2
import os
from pyvirtualdisplay import Display
from selenium import webdriver
import sys
display = Display(visible=0, size=(800, 600))
display.start()
try:
capabilities = webdriver.common.desired_capabilities.DesiredCapabilities.CHROME
browser = webdriver.Chrome('/opt/chrome-driver/chromedriver', desired_capabilities=capabilities)
try:
browser.get('http://example.com')
browser.execute_script('return 1 + 1;')
finally:
browser.quit()
finally:
display.stop()
print 'Done'
And then run
seq 1 20 | parallel -j 5 ./test.py
I get a random number of errors like this:
Traceback (most recent call last):
File "./test.py", line 15, in <module>
browser.execute_script('return 1 + 1;')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute_script
{'script': script, 'args':converted_args})['value']
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: chrome not reachable
(Session info: chrome=50.0.2661.86)
(Driver info: chromedriver=2.21.371461 (633e689b520b25f3e264a2ede6b74ccc23cb636a),platform=Linux 3.19.0-59-generic x86_64)
If I remove the concurrency (parallel -j 1), it works.
If I remove Xvfb, it works.
What does this error mean, and how can I fix it (without giving up concurrency or virtual displays)?

Looks like starting xvfb has concurrency issues when starting. xvfb-run unreliable when multiple instances invoked in parallel
So I can fix this by requiring that xfvb sessions are started serially.
#!/usr/bin/env python2
import fcntl
import os
from pyvirtualdisplay import Display
from selenium import webdriver
import sys
import xvfbwrapper
display = None
browser = None
try:
with open('/tmp/xvfb.lock', 'w') as lock:
fcntl.lockf(lock, fcntl.LOCK_EX)
display = Display(visible=0, size=(800, 600))
display.start()
capabilities = webdriver.common.desired_capabilities.DesiredCapabilities.CHROME
browser = webdriver.Chrome('/opt/chrome-driver/chromedriver', desired_capabilities=capabilities)
browser.get('http://example.com')
browser.execute_script('return 1 + 1;')
finally:
if browser:
browser.quit()
if display:
display.stop()
print 'Done'
As long as everybody uses /tmp/xvfb.lock to control starting a Xvfb session starting, this works.
P.S. I don't think the selenium driver starting needed to be serialized too, but I did run into a transient problem that I think was fixed by this.

Related

Error message when importing .csv files into MySQL using Python

I am a novice when it comes to Python and I am trying to import a .csv file into an already existing MySQL table. I have tried it several different ways but I cannot get anything to work. Below is my latest attempt (not the best syntax I'm sure). I originally tried using ‘%s’ instead of ‘?’, but that did not work. Then I saw an example of the question mark but that clearly isn’t working either. What am I doing wrong?
import mysql.connector
import pandas as pd
db = mysql.connector.connect(**Login Info**)
mycursor = db.cursor()
df = pd.read_csv("CSV_Test_5.csv")
insert_data = (
"INSERT INTO company_calculations.bs_import_test(ticker, date_updated, bs_section, yr_0, yr_1, yr_2, yr_3, yr_4, yr_5, yr_6, yr_7, yr_8, yr_9, yr_10, yr_11, yr_12, yr_13, yr_14, yr_15)"
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
for row in df.itertuples():
data_inputs = (row.ticker, row.date_updated, row.bs_section, row.yr_0, row.yr_1, row.yr_2, row.yr_3, row.yr_4, row.yr_5, row.yr_6, row.yr_7, row.yr_8, row.yr_9, row.yr_10, row.yr_11, row.yr_12, row.yr_13, row.yr_14, row.yr_15)
mycursor.execute(insert_data, data_inputs)
db.commit()
Error Message:
> Traceback (most recent call last): File
> "C:\...\Python_Test\Excel_Test_v1.py",
> line 33, in <module>
> mycursor.execute(insert_data, data_inputs) File "C:\...\mysql\connector\cursor_cext.py",
> line 325, in execute
> raise ProgrammingError( mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
MySQL Connector/Python supports named parameters (which includes also printf style parameters (format)).
>>> import mysql.connector
>>> mysql.connector.paramstyle
'pyformat'
According to PEP-249 (DB API level 2.0) the definition of pyformat is:
pyformat: Python extended format codes, e.g. ...WHERE name=%(name)s
Example:
>>> cursor.execute("SELECT %s", ("foo", ))
>>> cursor.fetchall()
[('foo',)]
>>> cursor.execute("SELECT %(var)s", {"var" : "foo"})
>>> cursor.fetchall()
[('foo',)]
Afaik the qmark paramstyle (using question mark as a place holder) is only supported by MariaDB Connector/Python.

Has PackageLoader changed with Jinja2 (3.0.1) and Python3 (3.9.5)?

I'm using Jinja2 (3.0.1), Python3 (3.9.5), and macOS (11.3.1).
These lines used to work:
from jinja2 import Environment, PackageLoader
e = Environment(loader = PackageLoader("__main__", "."))
but now produce:
Traceback (most recent call last):
File "/Users/downing/Dropbox/jinja2/Jinja2.py", line 36, in <module>
main()
File "/Users/downing/Dropbox/jinja2/Jinja2.py", line 31, in main
e = Environment(loader = PackageLoader("__main__", "."))
File "/usr/local/lib/python3.9/site-packages/jinja2/loaders.py", line 286, in __init__
spec = importlib.util.find_spec(package_name)
File "/usr/local/Cellar/python#3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/util.py", line 114, in find_spec
raise ValueError('{}.__spec__ is None'.format(name))
ValueError: __main__.__spec__ is None
Just discovered that FileSystemLoader still works and looks more appropriate for my use anyway.
The PackageLoader docs say:
Changed in version 3.0: No longer uses setuptools as a dependency.
which seems significant.
__main__.__spec__ can be None if __main__ isn't imported from a module. Probably python -m Jinja2 would still work for you, even if python Jinja2.py doesn't.
Like you, I switched to FileSystemLoader for this case, but I added a conditional to continue using PackageLoader when possible. That allows python -m path.to.my.module to continue working if the module is installed in a ZIP file or egg:
if __spec__ is not None:
loader = jinja2.PackageLoader('__main__')
else:
loader = jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), 'templates')
)
env = jinja2.Environment(loader=loader)

PyAutoGUI - No Such File or Directory Error

Anyone have any luck on this ? I am tyring to recreate this [tutorial code][1] :
>>> import pyautogui
>>> button7location = pyautogui.locateOnScreen('calc7key.png')
>>> button7location
(1416, 562, 50, 41)
>>> button7x, button7y = pyautogui.center(button7location)
>>> button7x, button7y
(1441, 582)
>>> pyautogui.click(button7x, button7y)
But I get the following error [at line 2 of the code above] FileNotFoundError: [Errno 2] No such file or directory: 'calc7key.PNG' when I have such file stored in File "C:\Users*******\Desktop\Python\lib\site-packages\pyscreeze__init__.py", line 165, in _locateAll_python
needleFileObj = open(needleImage, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'calc7key.PNG' ..anyone have any luck using this. essentially I am trying to screenshot a minimized tab to be opened by pyautogui (like lets say the google chrome icon at the bottom of my screen)
Solved : Had to change to the directory it was in
>>> import os
>>> os.chdir (r'C:\******')
>>>button7location = pyautogui.locateOnScreen('calc7key.png')
for me worked installing open cv: pip install opencv-python
(https://pypi.org/project/opencv-python/)
showing recommendation to install openCV

fipy - level set 1D

I am trying to run the code below for a level set 1D problem (example in fipy webpage). I am getting this error:
Traceback (most recent call last):
File "C:/Users/sgowda/Documents/pde solver code/level set 1D.py", line 20, in
var.calcDistanceFunction()
File "C:\Users\sgowda\AppData\Local\Continuum\Anaconda\lib\site-packages\fipy\variables\distanceVariable.py", line 335, in calcDistanceFunction
raise Exception, "Neither lsmlib nor skfmm can be found on the $PATH"
Exception: Neither lsmlib nor skfmm can be found on the $PATH
Could you please let me know how to fix this. i tried looking into the distancefucntion() but im not sure what this error means?
from fipy import Grid1D, CellVariable, TransientTerm, DiffusionTerm, Viewer, DistanceVariable
import matplotlib.pyplot as plt
velocity = 1.
dx = 1.
nx = 10
timeStepDuration = 1.
steps = 2
L = nx * dx
interfacePosition = L / 5.
from fipy.tools import serialComm
mesh = Grid1D(dx=dx, nx=nx, communicator=serialComm)
var = DistanceVariable(name='level set variable',
mesh=mesh,
value=-1.,
hasOld=1)
var.setValue(1., where=mesh.cellCenters[0] > interfacePosition)
var.calcDistanceFunction()
advEqn = TransientTerm() + FirstOrderAdvectionTerm(velocity)
viewer = Viewer(vars=var, datamin=-10., datamax=10.)
viewer.plot()
for step in range(steps):
var.updateOld()
advEqn.solve(var, dt=timeStepDuration)
viewer.plot()
plt.show()
FiPy doesn't have a native level set implementation so uses either LSMLIB or Scikit-fmm to provide the level set / fast marching method functionality.
To see whether you have them installed correctly, use either
$ python -c “import pylsmlib; pylsmlib.test()”
or
$ python -c “import skfmm; skfmm.test()”
to test.
The requirement is outlined in the FiPy documentation, see http://www.ctcms.nist.gov/fipy/INSTALLATION.html#level-set-packages
It is probably easier to install Scikit-fmm initially, see https://pythonhosted.org/scikit-fmm/, but
$ pip install scikit-fmm
should work.

Loading CPP functions into Python using Ctypes

I have a question to Ctypes and do not know what I do wrong. And yes, I am a newbie for Python and searched the other posts in here. So any advice is appreciated.
What do I want to do :
I simply want to load the FXCM C++ APP fundtions into Python 3.3 so I can call them for connecting to their server.
As it seems Ctypes seems to be the best tool. So a simple code in Python :
import os
dirlist = os.listdir('ForexConnectAPIx64/bin')
from pprint import pprint
pprint(dirlist)
from ctypes import *
myDll = cdll.LoadLibrary ("ForexConnectAPIx64/bin/ForexConnect.dll")
gives a result :
Traceback (most recent call File "C:\Users\scaberia3\Python_Projects \FTC\ListDir_Test.py", line 20, in <module>
myDll = cdll.LoadLibrary ("ForexConnectAPIx64/bin/ForexConnect.dll")
File "C:\Python33\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "C:\Python33\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden (Module not found)
['ForexConnect.dll',
'fxmsg.dll',
'gsexpat.dll',
'gslibeay32.dll',
'gsssleay32.dll',
'gstool2.dll',
'gszlib.dll',
'java',
'log4cplus.dll',
'msvcp80.dll',
'msvcr80.dll',
'net',
'pdas.dll']
Means the path is correct ForextConnect.dll is present and I might do some very simple wrong, but have no clue what.
You can either use Dependency Walker to figure out the correct sequence to manually load the DLLs, or simply add the directory to the system search path:
dllpath = os.path.abspath('ForexConnectAPIx64/bin')
os.environ['PATH'] += os.pathsep + dllpath
myDLL = CDLL('ForexConnect.dll')