I have several versions of wkhtmltopdf libraries installed on my server. I want to be able to switch between them programmatically when I'm about to render them because we have several development teams and they use different versions of wkhtmltopdf. Different wkhtmltopdf version are giving totally different rendered results, which is weird. Is it possible to switch between them programmatically?
This is not a full code but i try to this type of code may it's work for you:
import os
from openerp import tools # this odoo config file master/openerp/tools/which.py
import subprocess
import logging
_logger = logging.getLogger(__name__)
def find_in_path(name):
path = os.environ.get('PATH', os.defpath).split(os.pathsep)
if tools.config.get('bin_path') and tools.config['bin_path'] != 'None':
path.append(tools.config['bin_path'])
return tools.which(name, path=os.pathsep.join(path))
def _get_wkhtmltopdf_bin():
return find_in_path('wkhtmltopdf')
wkhtmltopdf_state = 'install'
try:
process = subprocess.Popen(
[_get_wkhtmltopdf_bin(), '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
print "prrrrrrrrrrrrrrrr", process.communicate()[0]
# here write your logic
#
#
#
#
except (OSError, IOError):
_logger.info('You need Wkhtmltopdf to print a pdf version of the reports.')
Related
I have a script that automates downloading a file using selenium and webdriver as chrome
basically, it logs in to a work website, and clicks on some settings to prepare to download a report file, and then clicks the download button
Is there a way for selenium or any other library to grab the file location and name of that file that is downloading or has just downloaded so I can store it in a variable to use later in the script
I do not know if the relative path will work or if it needs to be a full windows path name for it to work... probably safe to assume full path is more guaranteed to work
example being C:\Users\FunnyUserName\Downloads\report.xls
Adding Code to show what is happening better
#For Report Pull
#-----------------------------------------------
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import datetime
import os
import glob
###############################################################
#Pull Report #
###############################################################
#Open Web Driver
browser = webdriver.Chrome()
#Open Website and Log in
print('Open Website and Log In')
browser.get(('https://SomeWebsite.com'))
print('Working on Getting the QC Report')
print('Please Stand By')
#####
#I Removed a lot of stuff not necessary to this question
#Get the File
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[#id="btnGenerateReport"]'))).click()
time.sleep(4)
#Working on getting the last downloaded Filename
# get the user download folder (dynamic so will work on any machine)
downLoadFolder =os.path.join( os.getenv('USERPROFILE'), 'Downloads')
print(downLoadFolder)
#This shows the correct folder....
#In My Case C:\Users\My UserName\Downloads
# get the list of files
list_of_files = glob.glob(downLoadFolder+"/*.*") # * means all if need specific formats (if you are looking for any specific format then specify eg: "/*.xls" to filter)
print (list_of_files)
#Always Shows ['C:\\Users\\My UserName\\Downloads\\desktop.ini']
# get the latest file name
#Forced the Folder and file type as a test
latest_file = max(glob.glob("C:/Users/My Username/Downloads/*.xls"), key=os.path.getctime)
#print the latest file name
print(latest_file)
#Returns:latest_file = max(glob.glob("C:/Users/My Username/Downloads/*.xls"), key=os.path.getctime)
#ValueError: max() arg is an empty sequence
I might have figured out where the problem is
I need it to grab the actual downloads directory, not the system default
I'm testing on my home computer, it default downloads to my dropbox download directory that I share with my work computer as well
so its not C:\Users\My Username\Downloads\
its actually D:\Dropbox\Downloads... which is where my chrome default is set currently
how do I get the chrome download directory?
Here is the solution in the python.
Imports Needed:
import glob
import os
Script:
# get the user download folder (dynamic so will work on any machine)
downLoadFolder =os.path.join( os.getenv('USERPROFILE'), 'Downloads')
# get the list of files
list_of_files = glob.glob(downLoadFolder+"/*") # * means all if need specific formats (if you are looking for any specific format then specify eg: "/*.xlsx" to filter)
# get the latest file name
latest_file = max(list_of_files, key=os.path.getctime)
#print the latest file name
print(latest_file)
myapp.py
---- import statements ---
parser = None
app = Flask(__name__)
#app.route('/xxxxxx/yyy')
def markDealStatud():
text = 'matthew honnibal created spacy library'
parsedData = parser(text.decode("utf-8"))
xxxxxxxxxxxxx
xxxxxxxxxxxx
def initSpacy():
global parser
parser = English()
if __name__ == '__main__':
initSpacy()
app.run()
if __name__ == 'myapp':
initSpacy()
when i run this app in development mode, __main__ will execute and it will instantiate spacy only once and i will use that.
For production we are using apache server mod_wsgi configuration. similarly i want to instantiate it once(myapp) and use the same obj.
In my configuration it is instantiating for each request. Suggest some solution plz.
Environment
Operating System: Linux
Python Version Used: 2.7
Environment Information: apache mod_wsgi deployment
I started to learn Scrapy but I stuck up at weird point where I couldn't set default shell to ipython. The operating system of my laptop is Ubuntu 15.10. I also installed ipython and scrapy. They run well without causing any errors.
According to Scrapy's official tutorial, I can change my default scrapy shell by entering this in the global configuration file
[settings]
shell = ipython
The problem is I couldn't locate the configuration file. I tried following instructions from another page.
I made these three config files in
/etc/scrapy.cfg (system-wide),
~/.config/scrapy.cfg ($XDG_CONFIG_HOME) and ~/.scrapy.cfg ($HOME) for global (user-wide) settings.
but It didn't help at all.
what should I do?
I followed the instruction in the first answer by paul trmbrth. There still seems to be a problem though.
seems like I do have a right configuration file in the right place. But I still cannot open scrapy shell with ipython, as you can see in the screenshot. Have any idea?
Another way to configure (or test) the shell used by scrapy shell is the SCRAPY_PYTHON_SHELL environment variable.
So running:
paul#paul:~$ SCRAPY_PYTHON_SHELL=ipython scrapy shell
would use ipython as first choice, whatever setting in *scrapy.cfg you may have.
To check where scrapy is looking for config files, and what it finds, you can start the python interpreter and run what scrapy shell does:
$ python
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from scrapy.utils.conf import get_config, get_sources
>>> get_sources()
['/etc/scrapy.cfg', 'c:\\scrapy\\scrapy.cfg', '/home/paul/.config/scrapy.cfg', '/home/paul/.scrapy.cfg', '']
>>> cfg = get_config()
>>> cfg.sections()
['deploy', 'settings']
>>> cfg.options('settings')
['shell']
>>> cfg.get('settings', 'shell')
'bpython'
If you are inside of the project you can use this:
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
settings.get('IMPORT_API_URL')
If you are outside of the project, you can use this:
from scrapy.settings import Settings
settings = Settings()
settings_module_path = os.environ.get('SCRAPY_ENV', 'project.settings.dev')
settings.setmodule(settings_module_path, priority='project')
settings.get('BASE_URL')
I'm developing an automatic web tester using Selenium (v2.37.2). Program works properly until I run the test built with cxfreeze (there is also tkinter gui).
there is the init function
def initDriver(self):
if self.browser == FIREFOX:
profile = webdriver.FirefoxProfile(profile_directory=self.profile);
self._driver = webdriver.Firefox(firefox_profile=profile)
elif self.browser == CHROME:
self._driver = webdriver.Chrome(self.executable, chrome_options=profile)
elif self.browser == IEXPLORER:
self._driver = webdriver.Ie(self.executable)
Now when I build it using Cx_freeze I get this error
method redirectToBlank(...) calls initDriver(..) as the first thingSo how I pack the .xpi file to the library.zip file - which option in setup.py I have to use? And do I even have to this?
And the second strange thing is, that the other browsers work fine, when I execute the .exe file in by clicking on its icon, but when I run it from command line, I get errors even for chrome and IE. (Sorry that the traceback isn't complete)
All paths are relative from the executed file (no matter from where you run it),
Thank you for any ideas to solve this problem.
(method redirectToBlank(...) calls initDriver(..) as the first thing)
First issue solved
It's problem with selenium - FirefoxProfile - class, which tries to load webdriver.xpi as a normal file, but selenium pack all libraries to a zip file, so selenium can't find it.
Even forcing cx_freeze in setup file to add webdriver.xpi to a proper directory in zip won't help.
It is necessary to edit FirefoxProfile (in firefox_profile module) class for example like this
def _install_extension(self, addon, unpack=True):
"""
Installs addon from a filepath, url
or directory of addons in the profile.
- path: url, path to .xpi, or directory of addons
- unpack: whether to unpack unless specified otherwise in the install.rdf
"""
if addon == WEBDRIVER_EXT:
# altered lines
import sdi.env
WEBDRIVER_SUBSTITUTE = "path/to/unpacked/webdrive.xpi"
addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_SUBSTITUTE)
# Original lines:
# addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
< the rest of the method >
Issue 2
OSError: win error 6: the handle is invalid problem wasn't caused by either cxfreeze or selenium. I run the final exe file from git bash. There's the problem. For some reason git bash doesn't open stdin for the program and that's why it fails. When I run it in standard windows command line, everything is ok or if i run it from git bash like program.exe < empty_file
what i did was remove selenium form packages list.
and put it inside includefiles, then it works.
like this :
includefiles = [(seleniumPackage,'')]
...
options = {'build_exe': {'includes':includes,
'excludes':excludes,
'optimize':2,
'packages':packages,
'include_files':includefiles,
...
I've created this question relative to my other one - How to include modules in Cx_freeze, but decided that wasn't really realtive to my current question.
When i freeze my program, which uses easygui, I get a whole bunch of errors about missing modules, Yes - easygui is installed Python32, And Yes - Easygui is in site - packages,
Any Help would be appreciated, and FYI i'm using the basic setup.py ;)
from cx_Freeze import setup, Executable
setup(
name = "GUIproject",
version = "0.1",
description = "Sample Test easygui",
executables = [Executable("GUIproject.py")])
The modules it reports are missing include PIL, StringIO, Tkinter and tkFileDialog.
It's probably fine - see this answer about why missing modules aren't a problem.
In this case, PIL is optional for Easygui, and the other 3 are Python 2 names. Easygui will import the Python 3 names instead (you're running Python 3.2) - something like this:
try:
import tkinter # Python 3
except ImportError:
import Tkinter as tkinter # Python 2
So you should get an output exe file anyway - try running it, and see if it works.