Python - process ended with exit code 3221225477 - python-3.x

I've searched on this forum for a possible workaround, and tried my best, but none is working. below is the issue. I've a function which process websocket data and dump into an excel
I tried to use a wrapper/loop around the function, but still its failing.
I am utilizing, xlwings to copy data to the excel as below
def websocket_data_process():
xw.Book(xcelfile).sheets[shets1].range('A40').options(index=False).value = futDf
----where futDf is pandas datafrme
The issue is whenever, I am editing the excel at 'A40' Range manually (while the funcion is running), I am getting error like process ended with exit 3221225477. (I googled and came to its a access denied issue). Is there any way that I can workaround this crash and again resume the function, once editing is down..

Not sure if this is what you want. You can ask for a pause. The solution below will only work with windows.
import os
os.system("pause")
or this will work with any system.
input('Press <ENTER> to continue')
Of course you need an statement such as
for i in range(50):
rng = f'A{i+1}'
if rng == 'A40':
input('Press <ENTER> to continue')
# Do your things here ...

thanks for the response, but I resolved it,
The issue happens because the xlwings trying to access the existing excel which is either locked or not available to access it.
solution: I've created an instance of Excel with xlwings context manager and provided full permissions to the account which is running the excel and it's been resolved.

Related

win32com.client Python - Excel task remains running after telling application to quit

I've seen a couple questions similar to this, but they both appear to involve VBA and not Python.
This is a relatively recent error, so I suspect it might have something to do with the fact that I'm using Python 3.7 now.
Basically, using the Dispatch method from win32com.client, I am able to open a new Excel workbook and make my edits as I always have been. However, for some reason, I am unable to tell the application to quit successfully.
Used to be that I could write:
self.excel_app.Quit()
But now, I'm getting an AttributeError, of all things. Saying the Excel.Application does not have a Quit() attribute. Again, this is Python 3.7. What happened?
[EDIT]
Relevant code:
import sys
from win32com.client import Dispatch
#...
class X(object):
def __init__(self):
#...
self.excel_app = Dispatch("Excel.Application")
self.report_workbook = self.excel_app.Workbooks.Add()
#...
def close_excel(self):
try:
self.excel_app.Quit()
except Exception as ex:
sys.stdout.write("Could not quit application.\n-> ({}) {}\n".format(ex.__class__.__name__, ex))
self.excel_app = None
The exception printed to the terminal is:
Could not quit application.
(AttributeError) Excel.Application.Quit
Turns out that my error was coming from the fact that I was still using threading.Thread as the base class for the object trying to do this. Apparently it doesn't work so well with the Dispatch Excel objects anymore, and I'm trying to move away from Threads anyway.

xlwings: Unable to import functions (UDFs) via xlwings ribbon

I'm trying to import a user-defined function(UDF) via xlwings but am encountering an issue. Upon pressing the import functions button in the xlwings ribbon, I receive the following run time error:
`Run_time error '1004
`Method of 'VBProject' of object '_Workbook' failed.'
According to the VBA debugger, the below module contains the problem:
Sub ImportXlwingsUdfsModule(tf As String)
' Fallback: This is called from Python as direct pywin32 calls were
' sometimes failing, see comments in the Python code
On Error Resume Next
ActiveWorkbook.VBProject.VBComponents.Remove
ActiveWorkbook.VBProject.VBComponents("xlwings_udfs")
On Error GoTo 0
**ActiveWorkbook.VBProject.VBComponents.Import tf**
End Sub
The .py file containing the UDF is saved in the same folder as the calling .xlsm workbook.
How do I rectify this so I can utilize UDFs?
Thanks to the xlwings team for providing a link that helped me resolve the issue.
One needs to ensure that Trust Access to VBA object model is enabled.
See: https://docs.xlwings.org/en/stable/udfs.html#one-time-excel-preparations
If you have trusted access to the VBA object model and you are getting a TypeError, there is an additional answer that applies to both versions 0.22.2 and 0.22.3 and maybe earlier.
In file Lib>Site-Packages>xlwings>udfs.py on line 651 or 652 (depending on the version) insert ".Item" where shown in the following:
xl_workbook.VBProject.VBComponents.Remove(xl_workbook.VBProject.VBComponents.Item("xlwings_udfs"))
I do not know why this works but it does. The original line does work in VBA with only modifications that apply to VBA syntax and the workbook reference. (i.e. see the VBA code in the question for an example.

Running console window in background for GUI using tkinter on Windows 10

So I have this GUI that I made with tkinter and everything works well. What it does is connects to servers and sends commands for both Linux or Windows. I went ahead and used pyinstaller to create a windowed GUI without console and when I try to uses a specific function for sending Windows commands it will fail. If I create the GUI with a console that pops up before the GUI, it works like a charm. What I'm trying to figure out is how to get my GUI to work with the console being invisible to the user.
The part of my code that has the issue revolves around subprocess. To spare you all from the 400+ lines of code I wrote, I'm providing the specific code that has issues. Here is the snippet:
def rcmd_in(server):
import subprocess as sp
for i in command_list:
result = sp.run(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdout=sp.PIPE, stderr=sp.STDOUT)
print(result.stdout)
The argument 'server' is passed from another function that calls to 'rcmd_in' and 'command_list' is a mutable list created in the root of the code, accessible for all functions.
Now, I have done my due diligence. I scoured multiple searches and came up with an edit to my code that makes an attempt to run my code with that console invisible, found using info from this link: recipe-subprocess. Here is what the edit looks like:
def rcmd_in(server):
import subprocess as sp
import os, os.path
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
for i in command_list:
result = sp.run(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdin=sp.PIPE, stdout=sp.PIPE,
stderr=sp.STDOUT, startupinfo=si, env=os.environ)
print(result.stdout)
The the problem I have now is when it runs an error of "Error:8 - Internal error -109" pops up. Let me add I tried using functions 'call()', 'Popen()', and others but only 'run()' seems to work.
I've reached a point where my brain hurts and I can use some help. Any suggestions? As always I am forever great full for anyone's help. Thanks in advance!
I figured it out and it only took me 5 days! :D
Looks like the reason the function would fail falls on how Windows handles stdin. I found a post that helped me edit my code to work with pyinstaller -w (--noconsole). Here is the updated code:
def rcmd_in(server):
import subprocess as sp
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
for i in command_list:
result = sp.Popen(['C:/"Path to executable"/rcmd.exe', '\\\\' + server, i],
universal_newlines=True, stdin=sp.PIPE, stdout=sp.PIPE,
stderr=sp.PIPE, startupinfo=si)
print(result.stdout.read())
Note the change of functions 'run()' to 'Popen()'. The 'run()' function will not work with the print statement at the end. Also, for those of you who are curious the 'si' variable I created is preventing 'subprocess' from opening a console when being ran while using a GUI. I hope this will become useful to someone struggling with this. Cheers

Pygsheets and AWS Lambda

I am sure the suggestions here will be to use an S3 bucket and I am aware of this. My question is a bit more difficult, from what I am gathering, in that I want to use Pygsheets, a python library, to write to a Google Sheet. However, after getting through all the deployment and layer steps... what is stopping me is a pesky .json file needs to be read by one of the functions in Pygsheets. I do believe it is reading and writing something else on the fly which may not be allowed in and of itself but I am asking regardless.
Link directly to the function that needs to be used in conjunction with the secret.json from Google: Pygsheets Github
Sample code:
print("-->Using the library pygsheets to update...")
print(f"-->Accessing client_secret.json")
gc = pygsheets.authorize(service_file='client_secret.json')
print(f"-->Opening Google Sheets")
#open the google spreadsheet
sh = gc.open_by_url('https://...')
print(f"-->Accessing")
#select the first sheet
wks = sh[0]
print(f"-->Updating selected cells... ")
#update the first sheet with df, starting at cell A11.
wks.set_dataframe(df, 'J14')
Again, I am close to my final product of automating my sheets using this script/library/lambda that I can taste it :). If the absolute best workaround is S3 please be gentle I am a first year analyst trying to get my feet wet. Superior is telling me it would take a while to hook up a connection to S3 so thats also a reason to avoid. Thanks!
Fixed. Simply added the .json creds to the deployment package. I had ran into an issue with pandas so I have a blend of layers and a deployment package with my .py script (and, again, with secret.json). Thanks!

accessing clipboard via win32clipboard

I am working on a project in which i have to continuouly check clipboard content. If clipboard content matches with certain specified data, then it should be deleted from clipboard.
After doing a lot of googling, I find out that it can be done easily by win32clipboard api.
I am using Python as a programming language.
Following is a code for file(CF_HDROP) format:
import win32clipboard
import win32con
def filecopy():
try:
win32clipboard.OpenClipboard()
print win32clipboard.GetClipboardData(win32con.CF_HDROP)
win32clipboard.CloseClipboard()
except TypeError:
pass
Following is a code for text format:
import win32clipboard
def textcopy():
try:
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
print data
win32clipboard.CloseClipboard()
except TypeError:
pass
I am calling above functions in a infinite loop.
Individual function works correctly. But the problem with win32clipboard is that,
after win32clipboard.OpenClipboard() command, win32clipboard lock the clipboard and only realise it after CloseClipboard() command. In between i cant copy anything in clipboard.
How can i solve this problem??
Any other suggestion are also welcome to achieve ultimate aim.
NOTE: Its not necessary to use python. You can use any other language or any other approach.
An infinite polling loop (especially one without delays) is going to be a problem since there's no way to read the contents without locking. Instead you should look into becoming a Clipboard viewer (pywin32 and msdn), that way you are notified of the clipboard contents change and then you can inspect it (get it and get out). If you google a bit on pywin32 and WM_DRAWCLIPBOARD, you'll find some python implementations.

Resources