How could I close Excel file using pywinauto - python

I'm having a problem that I can't excel file.
I was using swapy+pywinauto.
program export excel file with different name (ex. time..)
I used swapy to close the export excel.
from pywinauto.application import Application
app = Application().Start(cmd_line=u'"C:\\Program Files\\Microsoft Office\\Office14\\EXCEL.EXE" \\dde')
xlmain = app.XLMAIN
xlmain.Wait('ready')
xlmain.Close()
app.Kill_()
but got error below.
Traceback (most recent call last):
File "D:/23007.py", line 54, in <module>
xlmain.Wait('ready')
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check_method_names))
File "C:\Python35\lib\site-packages\pywinauto\timings.py", line 308, in WaitUntil
raise err
pywinauto.timings.TimeoutError: timed out
Process finished with exit code 1

Why do you use app.XLMAIN? Is the title of window similar to XLMAIN? Usually the title is <file name> - Excel so that pywinauto can handle it so: xlmain = app["<file name> - Excel"].
Obviously Wait('ready') raised an exception because the window with title "XLMAIN" or similar is not found.
Generally I would recommend using pyWin32 standard module win32com.client to work with Excel (through standard COM interface). See the second answer here for example: Driving Excel from Python in Windows

Related

Unable to extract some files from zip file

I have made a python script which takes the latest files from university e-class (lectures in pdf formats, scripts etc) via requests and downloads them. After downloading it automatically extracts the zip on the specific folder i want. But the extraction function sometimes it gets stuck on the same files.
The function is this:
import zipfile
from tqdm import tqdm
zipnm = 'Διαδικτυακά και Φορητά Πληροφοριακά Συστήματα'
quartls = '6'
def extractZip(zipName, quartInd):
with zipfile.ZipFile('./'+zipName+'.zip', 'r') as zip_ref:
for member in tqdm(zip_ref.infolist(), desc='Extracting '):
try:
zip_ref.extract(member, './'+quartInd+'° εξάμηνο/'+zipName)
except zipfile.error as e:
print(e)
if __name__ == '__main__':
extractZip(zipnm, quartls)
When running on terminal it throws this:
PS Microsoft.PowerShell.Core\FileSystem::\\192.168.1.200\[REDACTED]> python .\test.py
Extracting : 39%|███████████████████████████ | 11/28 [00:00<00:01, 12.04it/s]
Traceback (most recent call last):
File "\\192.168.1.200\[REDACTED]\test.py", line 18, in <module>
extractZip(zipsd, quartsd)
File "\\192.168.1.200\[REDACTED]\test.py", line 12, in extractZip
zip_ref.extract(member, './'+quartInd+'° εξάμηνο/'+zipName)
File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1616, in extract
return self._extract_member(member, path, pwd)
File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1683, in _extract_member
os.mkdir(targetpath)
FileExistsError: [WinError 183] Δεν είναι δυνατή η δημιουργία ενός αρχείου όταν αυτό το αρχείο υπάρχει ήδη: '6° εξάμηνο\\Διαδικτυακά και Φορητά Πληροφοριακά Συστήματα\\Εργαστήρια\\Lab 5 - Introduction to PHP'
When I'm trying to extract the zip file manually, it sticks on 2 files that I either can retry or abort the files from extracting. Although the other files that already exist show me the options to replace them. My question is, why is this happening on these 2 files and not letting me to replace them like the others? Are the files corrupted (although I checked their size and looking if EOF is missing but nothing suspicious)?
P.S. I don't want on my script file to check if exists to exclude them I just want to find the source of the problem so I can act accordingly.
P.S.#2:
The files that get extracted are actually in an Ubuntu server machine which I access via Samba on Windows and then I run the script or doing anything with the files.

How do I download a file from a website in python without the users username?

So I am trying to make a download tool to download stuff via a link here is a snippet from my code
if download_choice == "14":
print("Downloading test file to Desktop...")
myfile14 = requests.get(url14)
open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content)
I want to make a program that can download stuff via a link. I want it to run on all PCs not only on mine. Here is the error:
Traceback (most recent call last): File "C:\Users\David\Desktop\Windows Download Tool\Python\WDT.py", line 100, in <module> open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content) FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/%userprofile%/desktop/'
Python does not use %userprofile% to get the username of the executing user.
To achieve this, you need to import the package os and run it's getlogin function. This returns a string with the current username
Example:
import os
username = os.getlogin()
if download_choice == "14":
print("Downloading test file to Desktop...")
myfile14 = requests.get(url14)
open(f'C:/Users/{username}/desktop/', 'wb').write(myfile14.content)
I am using an f-string for opening the file, since it is preferred by PEP-8 (it's just correct code-styling)
Attention: This only works on a windows machine

Why does the iMessage program throw a database error?

I'm a beginner and I've tried creating a iMessage program that sends a single word from a song's lyrics until it reaches the end. Unfortunately, I have encountered an error that I don't understand a single bit. I have tried researching about the bug, but I only see posts about actual SQL, and I haven't used it before.
It only sends one message and then throws errors like these:
Traceback (most recent call last):
File "/Users/levs/OneDrive/python/python-projects/14/messagebot.py", line 21, in <module>
sendMessage("+44 7871579435", getLyrics())
File "/Users/levs/OneDrive/python/python-projects/14/messagebot.py", line 18, in sendMessage
imessage.send(phone, message)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/py_imessage/imessage.py", line 16, in send
db_conn.open()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/py_imessage/db_conn.py", line 21, in open
db = sqlite3.connect(db_path, uri=True)
sqlite3.OperationalError: unable to open database file
And this is the code:
from time import sleep
from py_imessage import imessage
def getLyrics():
with open('lyrics.txt') as file:
return ' '.join([str(line.strip()) for line in file])
def getWords(lyrics):
return lyrics.split()
def sendMessage(phone, lyrics):
for message in getWords(lyrics):
imessage.send(phone, message)
sendMessage("+44 1122334455", getLyrics())
I would appreciate any kind of help! :)
I did a bit of research on the py_imessage package. It works by accessing the iMessages database on your Mac. The error message you are seeing,
sqlite3.OperationalError: unable to open database file
basically means that your Mac is not allowing the program to access that database. To fix this issue, you will need to boot your Mac into Recovery Mode and run:
crsutil disable
in the terminal. This can be done by holding Command-R when restarting your Mac. Once it boots into Recovery mode, go to Utilites > Terminal, and run csrutil disable there. Then you can type reboot and boot back into normal MacOS.

Pdb error while debugging python app with serverless launched offline

I have problem with debugging my view function with
import pdb; pdb.set_trace()
placed inside it and serverless launched as
> sls offline start
in console.
Namely, making correspondent GET request I receive the following error:
Python: > /.../handler.py(88)get_results()
-> request_params = event.query_params
Python: (Pdb)
Python: 2019-02-20 18:37:43,648 [ERROR] | ...
Traceback (most recent call last):
...
File ".../handler.py", line 88, in get_results
...
File "/usr/lib/python3.6/bdb.py", line 51, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib/python3.6/bdb.py", line 70, in dispatch_line
if self.quitting: raise BdbQuit
bdb.BdbQuit
Google suggests that the problem is in the inability of serverless process to read from stdin, but I don't know how to handle this problem.
Any suggestions?
I found a solution here https://stackoverflow.com/a/26975795/4388451:
create two fifos:
mkfifo fifo_stdin
mkfifo fifo_stdout
in one terminal
In the same terminal open stdout on background, and write to stdin:
cat fifo_stdout & cat > fifo_stdin
In python code create the the pdb object, and use it:
import pdb
mypdb = pdb.Pdb(stdin=open('fifo_stdin', 'r'), stdout=open('fifo_stdout', 'w'))
....
mypdb.set_trace()
Run python code from the folder where fifos were placed (or place fifos in the first step in the folder with python code) in another terminal
Now I am able to use pdb in first console!
PS
It is useful to use --noTimeout option while debugging: sls offline --noTimeout

Getting "global name 'FbxManager' is not defined"

I am working on creating a WebGL interface for which I am trying to convert FBX models to JSON file format in an automated process using python file, convert_fbx_three.py (from Mr. Doob's GitHub project) from command line.
When I try the following command to convert the FBX:
python convert_fbx_three.py Dolpine.fbx Dolpine
I get following errors:
Error in cmd:
Traceback (most recent call last):
File "convert_fbx_three.py", line 1625, in <module>
sdkManager, scene = InitializeSdkObjects()
File "D:\xampp\htdocs\upload\user\fbx\FbxCommon.py", line 7, in InitializeSdkObjects
lSdkManager = KFbxSdkManager.Create()
NameError: global name 'FbxManager' is not defined
I am using Autodesk FBX SDK 2012.2 available here on Windows 7.
Can you please try the following:
import FbxCommon
.
.
.
lSdkManager, lScene = FbxCommon.InitializeSdkObjects()
You probably need to add environment variables pointing to the folder that contains fbx.pyd, FbxCommon.py, and fbxsip.pyd prior to calling anything in those modules.

Categories