Python win32com open OpenOffice Calc (.xls) spreadsheet through Task Scheduler - python

I am trying to open an existing .xls document with OpenOffice using the Python 2.7 win32com module. The following script runs perfectly through an interpreter:
from win32com import client
import time
import string
def pathnameToUrl( cPathname):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = string.replace( cPathname, "\\", "/" )
cPathname = "file://" + cPathname
return cPathname
def PropertyValueArray(num):
'''Creates an openoffice property value array'''
l = []
for x in range(num):
_p = manager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
_p.Name = ''
_p.Value = ''
l.append(_p)
return l
wbcpath = r"C:\myexcelfile.xls"
manager = client.DispatchEx("com.sun.star.ServiceManager")
desktop = manager.CreateInstance("com.sun.star.frame.Desktop")
manager._FlagAsMethod("Bridge_GetStruct")
manager._FlagAsMethod("Bridge_GetValueObject")
p = PropertyValueArray(1)
p[0].Name = 'Hidden' # doc should run hidden
p[0].Value = True # doc should run hidden
doc = desktop.loadComponentFromURL(pathnameToUrl(wbcpath), "_blank", 0, p)
doc.store()
time.sleep(5)
doc.dispose()
When I try to schedule this under Windows Task Scheduler on Windows Server Standard 2007 SP2 if get the following error:
Traceback (most recent call last):
File "D:\report_polygon_count.py", line 216, in <module>
manager = client.DispatchEx("com.sun.star.ServiceManager")
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\__init__.py", line 113, in DispatchEx
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
com_error: (-2146959355, 'Server execution failed', None, None)
I am sure the issue is that the application wants to open a window and it is begin rejected because there is no user logged in. I have attempted to run it as hidden to avoid this issue. Is there a way to get round this or is it too ambitious?

Related

Spotify voice assistant attribute error __enter__

Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == input_mic:
m = Microphone(device_index=i)
while True:
"""
Commands will be entered in the specific format explained here:
- the first word will be one of: 'album', 'artist', 'play'
- then the name of whatever item is wanted
"""
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'album':
uri = get_album_uri(spotify=spotify, name=name)
play_album(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "album", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
the exact error is:
Traceback (most recent call last):
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
with m as source:
AttributeError: __enter__
__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
The error here is caused because m = None, and None cannot be used in a with statement.
>>> with None as a:
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__

Running into error <unknown>.SaveAsFile, no solution yet found via any non-token sources for extracting files from enterprise outlook

I created the next part of the program to extract specific attatchment from my active outlook:
import win32com.client as win32
import win32com
from tabulate import tabulate
import os
def findFolder(folderName, searchIn):
try:
lowerAccount = searchIn.Folders
for x in lowerAccount:
if x.Name == folderName:
objective = x
return objective
return None
except Exception as error:
print("Looks like we had an issue accessing the searchIn object")
print(error)
return None
outlook = win32com.client.Dispatch("Outlook.Application")
ons = outlook.GetNamespace("MAPI")
one = 'email#email.nl'
Folder1 = findFolder(one, ons)
inbox = findFolder('Postvak IN', Folder1)
messages=inbox.Items
ma = [["Subject", "Sender", "Attachment", "Saved?"]]
PathName = "C:\\Temp\\CV_BU_SQ"
os.chdir(PathName)
for msg in messages:
if msg.Class == 43 and "TLS NL_Commvault" in msg.SenderName and len(msg.Attachments) == 1:
CV_file = str(msg.Attachments.Item(1))
CV_pf = os.path.join(os.getcwd() + '\\' + CV_file)
res = "Yes!"
try:
msg.Attachments.SaveAsFile(os.getcwd() + '\\' + CV_file)
except Exception as e:
res = "No, error: " + str(e)
ma.append([msg.Subject[:30], msg.SenderName[:30], CV_file, res])
print(tabulate(ma,headers="firstrow"))
The output is:
Subject Sender Attachment Saved?
------------------------- ---------------- ---------------------------------------------------- -------------------------------
Backup Job Summary Report TLS NL_Commvault Commvault***DagelijkseBackup_2021-07-23-08-00-13.csv No, error: <unknown>.SaveAsFile
or raw error:
Traceback (most recent call last):
File "C:/Users/id983857/PycharmProjects/CheckCVMail/main.py", line 37, in <module>
msg.Attachments.SaveAsFile(os.getcwd() + '\\' + CV_file)
File "C:\Users\id983857\CheckCVMail\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.SaveAsFile
This outlook environment is based on Office 365, enterprise edition ...
Any e-mail extraction software demo-edition can not be tested, as this is an enterprise edition.
I do NOT need a token to read my mail per O365 or HTML, just my user account.
I don't have access to an non-enterprise O365.
I want to know what could be the reason for this error?
Any value to the SaveAsFile(...) results in the same error.
I hope somebody has a idea how to fix this.
Change the line
CV_file = str(msg.Attachments.Item(1))
to
CV_file = msg.Attachments.Item(1).FileName
and
msg.Attachments.SaveAsFile(os.getcwd() + '\\' + CV_file)
to
msg.Attachments.Item(1).SaveAsFile(os.getcwd() + '\\' + CV_file)
The Attachments property returns a collection of attachments. If you need to access the first attachment from the collection you can use the Item method:
msg.Attachments.Item(1)

How to run CANoe testmodule via Python?

I would like to be able to start a testmodule that is in my CANoe script; it works fine if I start everything without Python.
Now, my Python code can load CANoe, open the desired cfg, and start the simulation.
I tried some code from examples in the documentation and here, but it doesnt work...
# --------------------------------------------------------------------------
# Standard library imports
import os
import sys
import subprocess
# import win32com.client
import time
import threading
from win32com.client import *
from win32com.client.connect import *
my_xml_ts = r"C:\_my_path\boaz_test2.xml"
# Vector Canoe Class
class CANoe:
def __init__(self):
self.application = None
# check if there is any instance of CANoe process
# output = subprocess.check_output('tasklist', shell=True)
# if CANoe process is still available, kill the process
# if "CANoe32.exe" in str(output):
# os.system("taskkill /im CANoe32.exe /f 2>nul >nul")
# re-dispatch object for CANoe Application
self.application = win32com.client.DispatchEx("CANoe.Application")
self.ver = self.application.Version
print('Loaded CANoe version ',
self.ver.major, '.',
self.ver.minor, '.',
self.ver.Build, '...')#, sep,''
self.Measurement = self.application.Measurement.Running
print(self.Measurement)
def open_simulation(self, cfgname):
# open CANoe simulation
if (self.application != None):
# check for valid file and it is *.cfg file
if os.path.isfile(cfgname) and (os.path.splitext(cfgname)[1] == ".cfg"):
self.application.Open(cfgname)
else:
raise RuntimeError("Can't find CANoe cfg file")
else:
raise RuntimeError("CANoe Application is missing,unable to open simulation")
def set_testmodule(self):
print("set_testmodule start")
test_env = self.application.Configuration.TestSetup.TestEnvironments.Item("Test Environment")
print("set_testmodule 1")
test_env = win32com.client.CastTo(test_env, "ITestEnvironment2")
print("set_testmodule 2")
self.test_module = test_env.TestModules.Item("XML_Boaz_2")
print("set_testmodule end", self.test_module)
def test_module_run(self):
print("test_module_run start")
self.test_module.Start()
print("test_module_run end")
# {.Sequence} property returns a collection of <TestCases> or <TestGroup>
# or <TestSequenceItem> which is more generic
seq = self.test_module.Sequence
for i in range(1, seq.Count + 1):
# Cast from <ITestSequenceItem> to <ITestCase> to access {.Verdict}
# and the {.Enabled} property
tc = win32com.client.CastTo(seq.Item(i), "ITestCase")
if tc.Verdict != 1: # Verdict 1 is pass
tc.Enabled = True
print(f"Enabling Test Case {tc.Ident} with verdict {tc.Verdict}")
else:
tc.Enabled = False
print(f"Disabling Test Case {tc.Ident} since it has already passed")
def close_simulation(self):
# close CANoe simulation
if (self.application != None):
self.stop_Measurement()
self.application.Quit()
# make sure the CANoe is close properly, otherwise enforce taskkill
output = subprocess.check_output('tasklist', shell=True)
if "CANoe32.exe" in str(output):
os.system("taskkill /im CANoe32.exe /f 2>nul >nul")
self.application = None
def start_Measurement(self):
retry = 0
retry_counter = 5
# try to establish measurement within 20s timeout
while not self.application.Measurement.Running and (retry < retry_counter):
self.application.Measurement.Start()
time.sleep(1)
retry += 1
if (retry == retry_counter):
raise RuntimeWarning("CANoe start measuremet failed, Please Check Connection!")
and running that:
import Python_CANoe
import time
import random
def try2():
X = random.randrange(50)
Y = random.randrange(100)
print("start")
CANoe = Python_CANoe.CANoe()
CANoe.open_simulation(canoe_config_file)
CANoe.set_testmodule() # Doesn't work
print("CANoe script already Open")
CANoe.start_Measurement()
time.sleep(5)
CANoe.test_module_run() # Doesn't work
if __name__ == "__main__":
try2()
and this is the error code I am getting:
set_testmodule start
Traceback (most recent call last):
File "C:/Users/m.m/Documents/Python/CANoe_Python_Script/7_5_2021_3_for_stackoverflow/CANoe_Boaz_Test.py", line 133, in <module>
try2()
File "C:/Users/m.m/Documents/Python/CANoe_Python_Script/7_5_2021_3_for_stackoverflow/CANoe_Boaz_Test.py", line 77, in try2
CANoe.set_testmodule() # Doesn't work
File "C:\Users\m.m\Documents\Python\CANoe_Python_Script\7_5_2021_3_for_stackoverflow\Python_CANoe.py", line 52, in set_testmodule
test_env = self.application.Configuration.TestSetup.TestEnvironments.Item("Test Environment")
File "C:\Users\BOAZ~1.BIL\LOCALS~1\Temp\gen_py\3.7\7F31DEB0-5BCC-11D3-8562-00105A3E017Bx0x1x58.py", line 15873, in Item
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'TestEnvironments::Item', 'Invalid index: Item not found!', 'C:\\Program Files\\Vector CANoe 11.0\\Help01\\CANoeCANalyzer.chm', 4281, -2147467259), None)

IndexError: list index out of range for pyswip library

First of all I'm getting too many errors for python right now. This situation affected my motivation quite negatively. I'm trying to run an expert system that I found in this error. But I get the following error. I looked at other solutions but it didn't work for me either.
Drug Store Expert System:
https://github.com/enzoftware/pyswipl_drugstore
Code:
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from pyswip import Prolog
import os
import time
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
#app.route("/", methods=['GET', 'POST'])
def hello():
form = ReusableForm(request.form)
if request.method == 'POST':
name=request.form['name']
fiebre = request.form.get('fiebre') == 'on'
nausea = request.form.get('nausea') == 'on'
diarrea = request.form.get('diarrea') == 'on'
headache = request.form.get('headache') == 'on'
print(fiebre, nausea, diarrea, headache)
os.system('swipl -q -t "program" console.pl')
if form.validate():
f = open("file.txt", "r")
disease = f.read()
print(disease)
flash('Hola ' + name + ', por tus sintomas podemos deducir que tienes '+ disease)
else:
flash('Error: Debes ingresar tu nombre. ')
return render_template('hello.html', form=form)
if __name__ == "__main__":
app.run()
Error:
ERROR: The system was unable to find the specified registry key or value.
Traceback (most recent call last):
File "c:/Users/BAUM-PC/Desktop/Yeni klasör/pyswipl_drugstore-master/main.py", line 3, in <module>
from pyswip import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\__init__.py", line 29, in <module>
from pyswip.prolog import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\prolog.py", line 28, in <module>
from pyswip.core import *
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 568, in <module>
(_path, SWI_HOME_DIR) = _findSwipl()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 411, in _findSwipl
(path, swiHome) = _findSwiplWin()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 208, in _findSwiplWin
match = pattern.match(ret[-1])
IndexError: list index out of range
core.py
(related section)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
Windows Solution:
Make sure your Python and SWI Prolog are both 32- or 64-bit.
Go to line 180 of core.py and change the line to this:
paths = [os.path.join(programFiles, r'swipl\bin', dllName)
For first error:
As per official documentation of Pyswip you must take care of version of python and SWI-Prolog.
Make sure the SWI-Prolog architecture is the same as the Python architecture. If you are using a 64bit build of Python, use a 64bit build of SWI-Prolog.
For second error:
When you are accessing ret[-1] in match = pattern.match(ret[-1]) the index of list ret is not available.

AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'

I'm currently trying to use the pjsip api pjsua in python and therefor studying this Hello World example: http://trac.pjsip.org/repos/wiki/Python_SIP/Hello_World
I copied the code over, integrated account configuration according to http://trac.pjsip.org/repos/wiki/Python_SIP/Accounts etc. But when I run the sample, I get the following output:
Traceback (most recent call last):
File "/home/dmeli/workspace/eit.cubiephone.sip_test/eit/cubiephone/sip_test/hello.py", line 48, in <module>
acc = lib.create_account(acc_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2300, in create_account
err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 900, in _cvt_to_pjsua
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Because I'm not really a python expert and never worked with PJSIP before, I can't really figure out the error. Too me, it looks like it's actually an error in the pjsip python wrapper. But what do I know?
Code:
lib = pj.Lib()
lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
transport = lib.create_transport(pj.TransportType.UDP)
lib.start()
acc_cfg = pj.AccountConfig("XXXXX", "XXXXXX", "XXXXXX")
acc_cfg.id = "sip:XXXXXXX#XXXXXXXX"
acc_cfg.reg_uri = "sip:XXXXXXXXX"
acc_cfg.proxy = [ "sip:XXXXXXXXX;lr" ]
acc = lib.create_account(acc_cfg)
# Make call
call = acc.make_call("XXXXXXXXXXX", MyCallCallback())
Line where the error happens in pjsua.py:
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
(rtp_transport_cfg doesn't seem to have a member _cvt_to_pjsua()??)
For further work correctly, look at the PJSIP api (pjsua.py) that he is waiting for the order and structure!!!
## start lib.
def start(self):
try:
self._start_lib()
self._start_acc()
except pj.Error:
print "Error starting lib."
def _bind(self):
try:
t = pj.TransportConfig()
t.bound_addr = '0.0.0.0'
t.port = 5060
acc_transport = "udp" # depend if you need.
if acc_transport == "tcp":
self.transport = self.lib.create_transport(pj.TransportType.TCP, t)
# or this pj.TransportConfig(0) is creating random port ...
#self.transport = self.lib.create_transport(pj.TransportType.TCP, pj.TransportConfig(0))
else:
self.transport = self.lib.create_transport(pj.TransportType.UDP, t)
#self.transport = self.lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
except pj.Error:
print "Error creating transport."
#you need create callbacks for app, to work incoming calls, check on the server that returns the error code 200, and such a way your program will know that you are logged on correctly
#from callback.acc_cb import acc_cb
#self.acc_t = self.lib.create_account_for_transport(self.transport, cb=acc_cb())
def _start_lib(self):
self.lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
self.lib.start()
self._bind()
#codecs.load_codecs()
def _start_acc(self):
#from callback.acc_cb import acc_cb
try:
proxy = "sip server ip" # or proxy = socket.gethostbyname(unicode("sip.serverdnsname.com")) is needed to import socket
login = "Atrotygma" # real username
password = "Atrotygma_password" # real username
lib.create_account(acc_config=pj.AccountConfig(proxy, login, password))
except Exception, e:
print "Error creating account", e

Categories

Resources