I have an issue connecting to Lotus Notes from Python using win32com.client.
I am using the following code:
import win32com.client
import csv # imports the csv module
import sys # imports the sys module
import re
notesServer = "AALMBX01/Server/..."
notesPass = "PASS"
#Connect to notes database on server
notesSession = win32com.client.Dispatch('Lotus.NotesSession')
notesSession.Initialize(notesPass)
db_name = 'mail\iizs.nsf'
db = notesSession.getDatabase(notesServer, db_name)
view = db.GetView("($All)")
doc = view.getFirstDocument()
And I get the following error:
(-2147352567, 'Exception occurred.', (0, u'NotesSession', u'Notes
error: Wrong Password. (Passwords are case sensitive - be sure to use
correct upper and lower case.)'
Also tried leaving password blank and disabling 'request password for LN applications' in the interface. With a blank password, I am getting the following error message:
(-2147352567, 'Exception occurred.', (0, u'NotesDatabase', u'Database
AALMBX01/Server/...!!mail\iizs.nsf has not been opened yet'
I have tried the following:
Using lnlib and get_session function.
Checking that notus.ini file is in place (C:\Users\iizs\NotesData in my case) and includes the reference to userid (tried adding the full path to userid file, which is located in C:\Users\iizs\NotesData\data).
Adding a value to HKEY_CURRENT_USER\Software\Lotus\Notes(optional-version)\NotesIniPath
Added the folder containing notes.ini file (C:\Users\iizs\NotesData) and user.id file (C:\Users\iizs\NotesData\data) to the PATH environment variable.
The error is still the same. Tried copying user.id to one of system folders too (system32) - did not help either.
Any suggestions?
import win32com.client
import pywintypes
from win32com.client import Dispatch
from win32com.client import constants
notesSession = Dispatch('Lotus.NotesSession')
dir(constants)
dir(notesSession)
Password = 'S3cretP455w0rd'
Server = 'yourserver/yourapp' # yourserver = '' if local
scPath = 'view.nsf'
notesSession.Initialize(Password)
HTH!!
Also, one 'gotcha' that happened for me was network drives - if your NOTES.INI file contains a network path, try deleting and adding it in the Python code:
[code]
import os
os.system('net use w: /delete')
os.system('net use w: \\\\apps\\NotesFolder')
[/code]
Related
I have the same exact problem than
Running a saved MS Access macro in python: ERROR
I' using the exact same code but with my Access File and Macro names, using the complete path as suggested but getting the same error.
import win32api,time
from win32com.client import Dispatch
strDbName = '\\server\folder\file.accdb'
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.DoCmd.RunMacro('test')
objAccess.Application.Quit()
My access is stored in a network path that I'm writing like this
strDbName = '\\server\folder\file.accdb'
I have also tried
strDbName = 'r\\server\folder\file.accdb'
but I always get the error "Microsoft Access can't open the database because it is missing, or opened exclusively by another user, or it is not an ADP file."
any clue?
Every time that i try to launch my notebook im getting the error below .
let's specify that im new worker on the project and the file config.py was created before that i joined the team.
Does anyone knows how to resolve it please?
The code actually done is
Requirements.txt
psycopg2==2.7.3.2.
SQLAlchemy==1.2.2
pandas==0.21.0
docker==3.3.0
python-json-logger
sshtunnel==0.1.4
jupyter
jupytext==1.2
geopy==2.2.0
errror detail
~/SG/notebooks/config.py in <module>
1 # Using jupytext
----> 2 c.NotebookApp.contents_manager_class = "jupytext.TextFileContentsManager"
3 c.ContentsManager.default_jupytext_formats = "ipynb,py"
NameError: name 'c' is not defined
code
the row causing the error in the notebook is
from src.util.connect_postgres import postgres_connexion
the content of the file connect_postgres
from sqlalchemy import create_engine
from config.util.database import TARGET_TEST_HOST, TARGET_PROD_HOST, \
TARGET_TEST_DB, TARGET_PROD_DB, TARGET_TEST_USER, TARGET_PROD_USER, SG_PROD_USER, SG_PROD_HOST
from config.secrets.passwords import TARGET_PROD_PWD, TARGET_TEST_PWD, SG_PROD_PWD
from sshtunnel import SSHTunnelForwarder
import psycopg2
def _create_engine_psg(user, db, host, port, pwd):
""" Returns a connection object to PostgreSQL """
url = build_postgres_url(db, host, port, pwd, user)
return create_engine(url, client_encoding='utf8')
def build_postgres_url(db, host, port, pwd, user):
url = 'postgresql://{}:{}#{}:{}/{}'.format(user, pwd, host, port, db)
return url
def postgres_connexion(env):
if env == 'prod':
return create_engine_psg_with_tunnel_ssh(TARGET_PROD_DB,
TARGET_PROD_USER, TARGET_PROD_PWD, SG_PROD_PWD,
SG_PROD_USER,
SG_PROD_HOST, TARGET_PROD_HOST)
else:
raise ValueError("'env' parameter must be 'prod'.")
config.py
c.NotebookApp.contents_manager_class = "jupytext.TextFileContentsManager"
c.ContentsManager.default_jupytext_formats = "ipynb,py"
I red that i can generate the file and then edit it.
when i tried to create the jupyter_notebook_config it is always in my personal directory of marczhr
/Users/marczhr/.jupyter/jupyter_notebook_config.py
but i want to be done in my something that i can push on git.
Hope that im clear ^^
Thank you,
Don't run the notebook from the directory with the configuration file.
The reason is that there is an import with a config module or package in the code listed. By launching the notebook from the directory with the configuration file, it will import that Jupyter configuration file, instead of the correct package or module, with the resulting error.
Instead, run it from somewhere else, or put the configuration file elsewhere.
Or perhaps best, take the two configuration lines and add them to the end of your /Users/marczhr/.jupyter/jupyter_notebook_config.py file, then remove the 2-3 line config.py file.
In the latter case, you can now launch the notebook server from anywhere, and you don't need to specify any configuration file, since Jupyter will automatically use the generated (with added lines) one.
If you want to keep the config.py file, then launch the Jupyter notebook server from another directory, and simply specify the full path, like
jupyter --config=$HOME/SG/notebooks/config.py
All in all, this is a classic nameclash upon import, because of identically named files/directories. Always be wary of that.
(I've commented on some other potential problems in the comments: that still stands, but is irrelevant to the current problem here.)
I'm trying to open password protected excel workbooks and found the code I've posted below on this page but when I try to impliment it I'm getting a sytaxError and an indentationEorror
xlpassword.py
import xlwings as xw
from autoit.autoit import AutoItError
import autoit
import threading
class _WB(object):
def __init__(self, path, password=None):
self.path = path
self.password = password
self.name = path
#staticmethod
def _handlepassword(password):#this line is giving the error
if password:
autoit.win_wait_active("[TITLE:Excel]", 5)
autoit.send(password)
autoit.send("{ENTER}")
def op(self):
try: # If already opened
autoit.win_activate("%s - Excel"%self.name)
self.book = xw.Book(self.path)
except AutoItError: # Else
t = threading.Thread(target=self._handlepassword, args=(self.password,))
t.start()
self.book = xw.Book(self.path)
t.join()
finally:
return self
def _wait(self):
autoit.win_wait_active("%s - Excel"%self.name, 1)
def close(self):
self._wait()
self.book.close()
autoit.win_close("Excel")
when I get to the def _handlepassword line I get the output
SyntaxError: unexpected EOF while parsing (<string>, line 1)
IndentationError: unexpected indent (<string>, line 1)
Which means when I import xlpassword.py into another python script, that new script fails to run
test_run.py
import pandas as pd
from xlpassword import * #I know this isn't best practice
PATH = "C:\\Path\\to\\my\\file.xlsx"
print(PATH)
wb = _WB(path=PATH, password='MyP8ssw0rd')
I'm using python 3.8.1 on a windows 10 machine, and I have tried to run the code in spyder, sublime, and Rstudio (I normally work in Rstudio but I thought that might be what's causing the problem.)
I have read up on classes, class methods, and static methods and I can't see what I'm doing wrong here so if anyone could provide assistance it would help a lot.
Since v0.16.1, xlwings supports opening of password protected workbooks out of the box:
import xlwings as xw
wb = xw.Book(password='mypassword')
See also the API Reference: https://docs.xlwings.org/en/stable/api.html#xlwings.Book
I am getting the following import error on Mac:
ImportError: No module named Conf_Reader
Here are the few initial lines of my Python code:
import dotenv
import os
import testrail
import Conf_Reader
#setup the testrail client and connect to the testrail instance
def get_testrail_client():
testrail_file = os.path.join(os.path.dirname(__file__),'testrail.env')
testrail_url = Conf_Reader.get_value(testrail_file,'TESTRAIL_URL')
client = testrail.APIClient(testrail_url)
..
..
..
So far tried with pip and not able to find any sources for doing its installation.
I have the same problem on Mac.
To avoid using other independence you can skip using env. but pass as variable:
# create a credential.py
TESTRAIL_URL='https://testrail.com/testrail'
TESTRAIL_USER='xxxxx'
TESTRAIL_PASSWORD = 'xxxxx'
# on your update_testrail.py
from credential import TESTRAIL_URL,
TESTRAIL_USER,
TESTRAIL_PASSWORD
testrail_url = TESTRAIL_URL
client = testrail.APIClient(testrail_url)
# Get and set the TestRail User and Password
client.user = TESTRAIL_USER
client.password = TESTRAIL_PASSWORD
They should have linked to https://bangladroid.wordpress.com/2016/08/20/create-separate-credential-files-for-selenium-python/
where it explains you make your own ‘Conf_Reader.py’ file is as below:
"""
A simple conf reader.
For now, we just use dotenv and return a key.
"""
import dotenv,os
def get_value(conf,key):
# type: (object, object) -> object
"Return the value in conf for a given key"
value = None
try:
dotenv.load_dotenv(conf)
value = os.environ[key]
except Exception,e:
print 'Exception in get_value'
print 'file: ',conf
print 'key: ',key
return value
I want to make an script in python that reads mails from Lotus Notes 8.5 and then create for each email an issue in jira but it returns me this error when I try to read the mails from Lotus:
Traceback (most recent call last):
File "from_Lotus_TO_Jira.py", line 46, in <module>
main()
File "from_Lotus_TO_Jira.py", line 39, in main
folder = notesDatabase.GetView('$Inbox')
File "C:\Python27\lib\site-packages\win32com\gen_py\29131520-2EED-1069-BF5D-00
DD011186B7x0x1x2.py", line 1849, in GetView
ret = self._oleobj_.InvokeTypes(1610743866, LCID, 1, (9, 0), ((8, 1),),pName
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'NotesDatabase',
u'Database server_name!!C:\\Users\\MYNAME\\AppData\\Local\\Lotus\\Notes\\Data\\ma
il202\\myname.nsf has not been opened yet', None, 0, -2147217441), None)
here is my .py file
import win32com.client
import pywintypes
import getpass
def main():
# Get credentials
mailServer = 'server_name'
mailPath = 'C:\Users\MYNAME\AppData\Local\Lotus\Notes\Data\mail202\myname.nsf'
mailPassword = ''
# Connect
notesSession = win32com.client.Dispatch('Lotus.NotesSession')
notesSession.Initialize(mailPassword)
notesDatabase = notesSession.GetDatabase(mailServer, mailPath)
# Get a list of folders
folder = notesDatabase.GetView('$Inbox')
document = folder.GetFirstDocument()
if __name__ == "__main__":
main()
Looking at http://www-01.ibm.com/support/docview.wss?uid=swg21308538
The full filepath (e.g. "C:\notes\data\r_apps\haha.nsf") may
optionally be used when accessing local databases on a workstation. If
you specify a server name, however, or if the code is running on a
server, you must use the path relative to the Notes data directory
("r_apps\haha.nsf").
I suggest either (a) not specifying a server or (b) only giving a relative path, ie mailPath = r'mail202\myname.nsf'.
You are using the Notes COM classes. There is a nice shortcut call for opening the current user's mail database. The NotesSession class contains a GetDbDirectory method, which returns a NotesDbDirectory object, and the NotesDbDirectory class contains an OpenMailDatabase method.
I'm not a Python guy so I can't vouch for the exact syntax, but it should be along the lines of this:
notesSession.Initialize(mailPassword)
notesDbDirectory = notesSession.GetDbDirectory('')
notesDatabase = NotesDbDirectory.GetMailDatabase()
Note that the argument to GetDbDirectory can be an empty string or the name of a Domino server. It should not make any difference, as the GetMailDatabase method follows the same procedure as the NotesDatabase.OpenMail method (which is not exposed via the COM interface, therefore it is unavailable to Python). I.e., it looks at the current user's Notes client configuration to locate either a server-based or local replica of the user's mail database.
Also note that if this code is intended to run on one machine but process mail for many users on one Domino server, then you can't use the GetMailDatabase method. In that case, using the relative path as in #Hugh-Bothwell's answer would be correct, although I would strongly recommend adding some defensive programming via a call to notesDatabase.IsOpen() in between the calls to the GetDatabase() and GetView().