I have two Excel Files and I can execute Macro ReadBM_AP_Data, but not PythonScript. For this function I used PyWin32 with the Function RunApplication
Here is the Python Code:
xl = win32com.client.Dispatch("Excel.Application", pythoncom.CoInitialize())
#C:\Users\dx5entir\PycharmProjects\pythonProject
xl.Workbooks.Open("C:/Users/dx5entir/PycharmProjects/pythonProject/FapsXML.xlsm")
xl.RunApplication("FapsXML.xlsm!Modul1.PythonScript()")
#xl.Application.Run('ReadEC_DC_Data.xlsm!Modul2.ReadBM_AP_Data()')
xl.Application.Quit()
If I open the Excel File and start PythonScript it works.
This is the Error Messages:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\dx5entir\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 205, in run
self.dispatch_events(self.event_queue)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 381, in dispatch_events
handler.dispatch(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\events.py", line 271, in dispatch
self.on_any_event(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 54, in on_any_event
start_xl()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 68, in start_xl
xl.Application.Run("FapsXML.xlsm!Modul1.PythonScript()")
File "<COMObject >", line 8, in Run
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\win32com\client\dynamic.py", line 368, in ApplyTypes
result = self.oleobj.InvokeTypes(
^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_Serror: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft Excel', "Das Makro 'FapsXML.xlsm!Modul1.PythonScript()' kann nicht ausgeführt werden. Das Makro ist möglicherweise in dieser Arbeitsmappe nicht verfügbar, oder alle Makros wurden deaktiviert.", 'xlmain11.chm', 0, -2146827284), None)
I implement a watchdog to trigger this Event, but it still works with the other macro, so I see no problem with that.
Name Excel Sheets:
Name of Module and Sub:
At the beginning my Excel Sheets had spaces. So I fixed that.
I tried other macros and they worked. This macro PythonScript is working when I start it manually in the Excel file.
I called the function per Button and not trigger it with a watchdog event. Same error.
I updated my PythonInterpreter to Python 3.11.1 and updated every Python Packages in my Enviroment
Im confused why this function doesn't work with this macro, when this macro works when i start it manually and other macros works when I use PyWin32. I have no clue to fix that problem. Any advices? :)
Related
I am trying to use pyinstaller to create a .exe for someone else to run. The program uses mysql to ping a sql database and return information from it. When I run the program in PyCharm and with pyinstaller --onedir, everything works fine. However, when I bundle the program with --onefile, I get this error and traceback when running:
Traceback (most recent call last):
File "main.py", line 266, in <module>
File "main.py", line 88, in main
File "main.py", line 108, in grabData
File "sql.py", line 12, in SQLconnect
File "mysql\connector\pooling.py", line 286, in connect
File "mysql\connector\connection_cext.py", line 101, in __init__
File "mysql\connector\abstracts.py", line 1095, in connect
File "mysql\connector\connection_cext.py", line 199, in _open_connection
TypeError: argument 6 must be str, not None
For reference, here is the relevant line in the _open_connection function call in connection_cext.py:
self._cmysql = _mysql_connector.MySQL(
buffered=self._buffered,
raw=self._raw,
charset_name=charset_name,
connection_timeout=(self._connection_timeout or 0),
use_unicode=self._use_unicode,
auth_plugin=self._auth_plugin,
plugin_dir=self._plugin_dir,
)
The __init__ of this file has this code snippet:
self._plugin_dir = os.path.join(
os.path.dirname(os.path.abspath(_mysql_connector.__file__)),
"mysql",
"vendor",
"plugin",
)
I believe this plugin directory is the reason my code is failing, but I do not know how to bypass this or set it so that it references the right file at runtime. I know pyinstaller creates a temp file at runtime, but I don't know how to get the module to use it as the plugin directory.
Any help would be greatly appreciated! I really really wanna keep it in --onefile mode for simplicity for the user, so any solutions that maintain that would be ideal. Thanks!
I am writing to a file from python, if the file is open in some process, python throws error.
To make it clear, I am writing to a excel file, I want it closed if already open.
This is below code I use to write to file -
writer = pd.ExcelWriter('file_Output.xlsx', engine='xlsxwriter')
file.to_excel(writer,index=False, sheet_name='Sheet1')
Which throws below error if the file - file_Output.xlsx is already open in excel.
Traceback (most recent call last):
File "pythonclose.py", line 311, in <module>
writer.save()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\excel.py", line 1952, in save
return self.book.close()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 306, in close
self._store_workbook()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 655, in _store_workbook
allowZip64=self.allow_zip64)
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\zipfile.py", line 1082, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'file_Output.xlsx'
If a file is open by an external program(such as MS Excel in this case), the file handle or control of the file is with the program. Python has no control over the file and cannot close/edit it. However, if you have the Process ID for the file, it is possible to kill the process by different means(for eg. using taskkill in Windows or even with Python).
im new to python. Im using Pycharm 2018.2 and the latest version on Anaconda. Im working on windows 10.
After solving all the problems with installing textract on win 10. I got a positive installation result using anaconda prompt. Additional i have import the Project Interpreter from the \continuum\anaconda3\python.exe
My Target is that i want to extract pdf text from large files so save this text as a .txt
I have tried the test_pdf.py files from textract but they dont work.
Here is the conclusion code:
"textract" is wrong written or cant be found (self translate from
german :-/)
So I tried my own as on the textract page. But it doesnt work...:
Code:
import textract
text = textract.process('pfad/large.pdf')
Results:
C:\Users\raz\AppData\Local\Continuum\anaconda3\python.exe "C:/Users/raz/Google Drive/FOM/Master/Master/NurText/Testo.py"
Traceback (most recent call last):
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\utils.py", line 85, in run
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 709, in init
restore_signals, start_new_session)
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/raz/Google Drive/FOM/Master/Master/NurText/Testo.py", line 2, in
text = textract.process('pfad/large.pdf')
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers_init_.py", line 77, in process
return parser.process(filename, encoding, **kwargs)
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\utils.py", line 46, in process
byte_string = self.extract(filename, **kwargs)
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\pdf_parser.py", line 28, in extract
raise ex
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\pdf_parser.py", line 20, in extract
return self.extract_pdftotext(filename, **kwargs)
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\pdf_parser.py", line 43, in extract_pdftotext
stdout, _ = self.run(args)
File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\utils.py", line 92, in run
' '.join(args), 127, '', '',
textract.exceptions.ShellError: The command pdftotext pfad/large.pdf - failed with exit code 127
------------- stdout -------------
------------- stderr -------------
Thanks for your help
[USING XLWINGS PACKAGE]
I'm attempting to open an excel spreadsheet (existing), write data to specified cells, and then use the workbook.save() function to save the file to a new file name (as not to overwrite)
Right now I currently have:
app = xw.App(visible = False)
wbMain = wx.Book('Example.xlsm') #Open premade excel file
sheetMain = wbMain.sheets['Example']
sheetMain.range('A1').value = 'Test' #Modify value of cell A1
wbMain.save('NewFileName.xlsm') #Save to new filename
wbMain.close() #Close current excel sheet
app.kill() #Kill program (may not work)
(Sorry about my formatting if it's off)
Here is my traceback:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\test_proj\main.py", line 34, in <module>
wbMain.save(NewFileName.xlsm)
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\main.py", line 688, in save
return self.impl.save(path)
---
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 472, in save
self.xl.SaveAs(os.path.realpath(path))
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
---
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft
Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0,
-2146827284), None)
I've tried lookin at the XLWings documentation and various other stackoverflow threads but none seemed to offer a solution that worked. Has anyone had the same issue before?
I had the same problem - turns out using the full path in wbMain.save('C:/xxx/NewFileName.xlsm') worked for me.
Credits to #aneroid for the help! See here: xlwings: Save and Close
I have just downloaded Python3.5 and have been trying to do a simple task (open an Excel file and remove the first three rows and various columns from the file) for several hours now with no success.
The lastest issue is happening when I try to open the file.
This is the only code:
import pandas as pd
df = pd.ExcelFile("January2016.xlsx")
I get the following error no matter what read option I use with pandas.
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\IPython\core\interactiveshell.py", line 2847, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-25-503f922e97e7>", line 1, in <module>
df = pd.ExcelFile("January2016.xlsx")
File "C:\Python35\lib\site-packages\pandas\io\excel.py", line 257, in __init__
self.book = xlrd.open_workbook(io)
File "C:\Python35\lib\site-packages\xlrd\__init__.py", line 422, in open_workbook
ragged_rows=ragged_rows,
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 833, in open_workbook_2007_xml
x12sheet.process_stream(zflo, heading)
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 548, in own_process_stream
self_do_row(elem)
File "C:\Python35\lib\site-packages\xlrd\xlsx.py", line 745, in do_row
value = error_code_from_text[tvalue]
KeyError: None
Please help!
You need to either use pd.ExcelFile.parse(...) or pd.read_excel. pd.ExcelFile isn't a method that parses excel files, you need the parse part, too.
I know this thread is 3 years old. Anyway hope this might help someone.
I came across this recently. I think the problem is caused by a image in the file. When I run the code in windows environment it works well. But when I run the code in ubuntu environment it gives a Traceback error.