Python win32COM - COM Error: Member not found. (0x-7ffdfffd) - python

I am working on a Python script which opens an excel using win32com and make modification to it.
I am facing an issue while calling objNewRange=objWrkBook.Worksheets('Sheet1').Range('$A$2:$T$15').
I am getting the error :
Run-time error -2147352573: Member not found.
The script works fine when I run it from python shell, but I am calling the same code from HP ALM. I am able to write specifically to a cell using 'Cells' method but it looks like Python is unable to find the Range method.
Below is the Code fragment
# Newin [PythonScript]
# Created by Application Lifecycle Management
# 7/7/2016 4:06:15 PM
# ====================================================
import win32com.client
import pythoncom
import xlsxwriter
import string
import os
import shutil
import pythoncom
import sys
import win32com.client as win32
import datetime
import imp
import argparse
import glob
import re
from xml.etree.ElementTree import parse, tostring
from xml.etree import ElementTree as et
# ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
# StrVerifyExpResults Function:
# Description: This is the main fucntion that is used to compare the expected values to the actual ones. This calls in subfucntions to perform different operations
# Debug - Boolean. Equals to false if running in [Test Mode] : reporting to Application Lifecycle Management
# ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def StrVerifyExpResults(strFileName, strFilePath, strCurrentTestCaseID, intRowNum):
'''Opening the Input sheet'''
#strFileOpenStatus ='Success'
strFileOpenStatus, objWrkBook=OpenInputSheet(strFileName, strFilePath)
if strFileOpenStatus=='Success':
'''Get all row numbers from the input sheet'''
objWrkSheet=objWrkBook.Worksheets('Sheet1')
objDataRange=GetUsedRowRange(objWrkBook, 'Sheet1')
#Getting Range where the Data Is available
objNewRange=objWrkBook.Worksheets('Sheet1').Range('$A$2:$T$15')
print objNewRange.Address
# ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Main Function:
# Description: This is the main fucntion that is used to compare the expected values to the actual ones. This calls in subfucntions to perform different operations
# Debug - Boolean. Equals to false if running in [Test Mode] : reporting to Application Lifecycle Management
# CurrentTestSet - [OTA COM Library].TestSet.
# CurrentTSTest - [OTA COM Library].TSTest.
# CurrentRun - [OTA COM Library].Run.
# ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def Test_Main(Debug, CurrentTestSet, CurrentTSTest, CurrentRun):
try:
# clear output window
TDOutput.Clear()
# TODO: put your code here
status=StrVerifyExpResults('input.xlsx','D:\\GVOL\\01 - Docs\\Automation\\WS Automation\\Input Sheet\\','1',2)
except pythoncom.com_error, (hr, desc, exc, arg):
TDOutput.Print("Run-time error %d: %s" % (hr, desc))
def OpenInputSheet(strFileName2, strFilePath2):
#excel = win32.gencache.EnsureDispatch('Excel.Application')
excel = win32.Dispatch('Excel.Application')
excel.Visible = False
wb = win32.GetObject(strFilePath2 + strFileName2)
ws = wb.Worksheets('Sheet1')
return ('Success', wb)

Related

Python saxonpy returns I/O error when transforming XML

I am trying to perform XSLT transform using saxonpy with Python code as attached:
from saxonpy import PySaxonProcessor
import os
class XMLProcessor:
proc = PySaxonProcessor(license = False)
def processXSLT2(self, sourceXmlDocPath, xsltStyleSheetPath):
# https://www.saxonica.com/saxon-c/doc1.2/html/saxonc.html#PyXslt30Processor
print(self.proc.version)
self.proc.set_cwd(os.getcwd()) #set the CWD first
xsltproc = self.proc.new_xslt30_processor()
output = xsltproc.transform_to_string(source_file = sourceXmlDocPath,
stylesheet_file = xsltStyleSheetPath)
return output
In my main py file, it is called using XMLProcessor.processXSLT2(XMLProcessor, LOCAL_XML_FILE, os.environ['LAMBDA_TASK_ROOT'] + '/metadata.xsl')
However, the console shows this error message:
Saxon/C 1.2.1 running with Saxon-HE 9.9.1.5C from Saxonica
Error
I/O error reported by XML parser processing D:\git\lambda\data\test.xml: unknown protocol: d
You're supplying a Windows filename to an interface that expects a URI.
You're also using a product that's very out of date: please move forward to SaxonC 12.x.

Syntax error while executing a python script to make a web application

this is my first time using pycharm and flask library. i am fairly new to advanced programing and i was trying to create an executable link for my program but im getting a syntax error. when i run the same script in idle without the flask functions and without the if __name__=="__main__": line in python IDLE, it works just as expected.
from flask import Flask
import os
import csv
import sqlite3
import tkinter.filedialog
import pandas as pd
from tkinter import filedialog
from tkinter import *
app=Flask(__name__)
#app.route('/')
k=Tk()
k.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
database=sqlite3.connect("C:\SQLiteStudio\data.db")
d=database.cursor()
task1="""CREATE TABLE z (
date DATE ,
time TIME ,
value_1 DOUBLE PRECISION ,
value_2 DOUBLE PRECISION ,
final_value DOUBLE
);"""
task2="""INSERT INTO z (date, time, value_1, value_2, final_value) VALUES (?,?,?,?,?)"""
#d.execute(task1)
out=pd.read_csv(k.filename, header=None)
print(len(out))
print(out.iloc[0])
row=1
if str(out.iloc[0,0])=='Date' and str(out.iloc[0,1])=='Time' and str(out.iloc[0,2])=='Lat' and str(out.iloc[0,3])=='Long' and str(out.iloc[0,4])=='Temp':
while row< len(out):
print(row)
d.execute(task2,out.iloc[row])
database.commit()
row+=1
else:
print("The data is not in expected format.")
database.close()
if __name__=="__main__":
app.run()
"C:\Users\Jay Paliwal\Desktop\Internship\venv\Scripts\python.exe"
"C:/Users/Jay Paliwal/Desktop/Internship/task 1.py"
File "C:/Users/Jay Paliwal/Desktop/Internship/task 1.py", line 13
k=Tk()
^
SyntaxError: invalid syntax
Process finished with exit code 1
this is the output I got. I was expecting a link to come which when one visited opens a dialogue box for the tkinter function used
You can't just have a decorator on its own. A decorator needs to state a function.
Your code should be in a function anyway.
(Note though, it makes no sense to try to use tkinter in a Flask app. Why are you using Flask at all here?)

Why is my Maltego tranform giving me a empty value error?

I'm right now trying to code a Maltego tranform to search through the Breach Compilation data, using query.sh
Code:
#!/usr/bin/env python
# Maltego transform for grabbing Breach Compilation results locally.
from MaltegoTransform import *
import sys
import os
import subprocess
email = sys.argv[1]
mt = MaltegoTransform()
try:
dataleak = subprocess.check_output("LOCATION OF QUERY.SH" + email, shell=True).splitlines()
for info in dataleak:
mt.addEntity('maltego.Phrase', info)
else:
mt.addUIMessage("")
except Exception as e:
mt.addUIMessage(str(e))
mt.returnOutput()
Empty value for #org.simpleframework.xml.Text(data=false,
required=true, empty=) on method 'value' in class
com.paterva.maltego.transform.protocol.v2api.messaging.TransformResponse$Notification
at line 26
Not sure what the problem is.
Turns out
else:
mt.addUIMessage("")
except Exception as e:
mt.addUIMessage(str(e))
that bit of code was the problem. Got it working just fine.

Using XLWings with parallel processing

So I am new to parallel processing, but I was starting to get it working for parsing multiple Excel files simultaneously. It works well with when I only use openpyxl, but that is a basic XML parser as I understand it. When I include the part that uses XLWings (I like to take advantage of its ability to evaluate equations in Excel for file verification purposes), I get the following error:
pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
This is roughly the code I use to initialize a new XLWings instance and load a workbook:
def openWorkbook(self, filePath):
app = xw.apps.add()
app.display_alerts = False
app.screen_updating = False
wb = self.app.books(filePath) #Note that this is called only once for each workbook.
app.screen_updating = True
app.quit()
Is there some way to get XLWings to open several simultaneous instances of Excel? Should I try doing something like this? If so, I am not sure how the initialization would work with giving threads over to XLWings.
So I figured out the solution, it was actually surprisingly easy. I just added pythoncom.CoInitialize() from pythoncom package before my xw.apps.add() call:
ParallelProcessController.py
from multiprocessing.dummy import Pool
from LoadWorkbook import openWorkbook
def callOpenWorkbookInParallel(self, lsExcelFiles):
pool = Pool(processes=3)
pool.map(openWorkbook, lsExcelFiles)
LoadWorkbook.py
import xlwings as xw
import pythoncom
def openWorkbook(self, filePath):
pythoncom.CoInitialize()
app = xw.apps.add()
wb = app.books(filePath)
app.quit()

how to unittest and mock for open funtion

I have read many article over the last 6 hours and i still don't understand mocking and unit-testing. I want to unit test a open function, how can i do this correctly?
i am also concerned as the bulk of my code is using external files for data import and manipulation. I understand that i need to mock them for testing, but I am struggling to understand how to move forward.
Some advice please. Thank you in advance
prototype5.py
import os
import sys
import io
import pandas
pandas.set_option('display.width', None)
def openSetupConfig (a):
"""
SUMMARY
Read setup file
setup file will ONLY hold the file path of the working directory
:param a: str
:return: contents of the file stored as str
"""
try:
setupConfig = open(a, "r")
return setupConfig.read()
except Exception as ve:
ve = (str(ve) + "\n\nPlease ensure setup file " + str(a) + " is available")
sys.exit(ve)
dirPath = openSetupConfig("Setup.dat")
test_prototype5.py
import prototype5
import unittest
class TEST_openSetupConfig (unittest.TestCase):
"""
Test the openSetupConfig function from the prototype 5 library
"""
def test_open_correct_file(self):
result = prototype5.openSetupConfig("Setup.dat")
self.assertTrue(result)
if __name__ == '__main__':
unittest.main()
So the rule of thumb is to mock, stub or fake all external dependencies to the method/function under test. The point is to test the logic in isolation. So in your case you want to test that it can open a file or log an error message if it can't be opened.
import unittest
from mock import patch
from prototype5 import openSetupConfig # you don't want to run the whole file
import __builtin__ # needed to mock open
def test_openSetupConfig_with_valid_file(self):
"""
It should return file contents when passed a valid file.
"""
expect = 'fake_contents'
with patch('__builtin__.open', return_value=expect) as mock_open:
actual = openSetupConfig("Setup.dat")
self.assertEqual(expect, actual)
mock_open.assert_called()
#patch('prototype5.sys.exit')
def test_openSetupConfig_with_invalid_file(self, mock_exit):
"""
It should log an error and exit when passed an invalid file.
"""
with patch('__builtin__.open', side_effect=FileNotFoundError) as mock_open:
openSetupConfig('foo')
mock_exit.assert_called()

Categories

Resources