windll.gdi32.GetPixel failed with pyautogui and Variables from configparser - pywin32

i was trying to do a config.ini with configpaser i got it working with this
from configparser import ConfigParser
#-------Message Config Start ------------#
config = ConfigParser()
config.read('config.ini')
#Devicename for Message Curls
Geraet = str = config['DEFAULT']['Geraet_Name']
YellowBellX = str = config['DEFAULT']['YellowBellXCoord']
YellowBellY = str = config['DEFAULT']['YellowBellYCoord']
it works for urls of telegram curl and Geraet Name works alsow
but when i use this for x y for pixelmatch i get error
Exeption windll.gdi32.GetPixel failed : return -1
if i change YellowBellX to Coords it works
YellowBellX = 355
YellowBellY = 219
this works and pixel match is correct with no error
but i want to use Variable in the Config File

Related

Python Program error - The process cannot access the file because it is being used by another process

I am trying to test a python code which moves file from source path to target path . The test is done using pytest in Python3 . But I am facing a roadblock here. It is that , I am trying to remove the source and target paths at end of code completion. For this I am using a command like shutil.rmtree(path) or os.rmdir(path) . This is causing me the error - " [WinError 32] The process cannot access the file because it is being used by another process". Please help me on this. Below is the python pytest code :
import pytest
import os
import shutil
import tempfile
from sample_test_module import TestCondition
object_test_condition = TestCondition()
#pytest.mark.parametrize("test_value",['0'])
def test_condition_pass(test_value):
temp_dir = tempfile.mkdtemp()
temp_src_folder = 'ABC_File'
temp_src_dir = os.path.join(temp_dir , temp_src_folder)
temp_file_name = 'Sample_Test.txt'
temp_file_path = os.path.join(temp_src_dir , temp_file_name)
os.chdir(temp_dir)
os.mkdir(temp_src_folder)
try:
with open(temp_file_path , "w") as tmp:
tmp.write("Hello-World\n")
tmp.write("Hi-All\n")
except IOError:
print("Error has occured , please check it.")
org_val = object_test_condition.sample_test(temp_dir)
print("Temp file path is : " + temp_file_path)
print("Temp Dir is : " + temp_dir)
shutil.rmtree(temp_dir)
print("The respective dir path is now removed.)
assert org_val == test_value
Upon execution of the code , the below error is popping up :
[WinError32] The process cannot access the file because it is being used by another process : 'C:\Users\xyz\AppData\Local\Temp\tmptryggg56'
You are getting this error because the directory you are trying to remove is the current directory of the process. If you save the current directory before calling os.chdir (using os.getcwd()), and chdir back to that directory before removing temp_dir, it should work.
Your code isn't correctly indented, so here is my best guess at what it should look like.
import pytest
import os
import shutil
import tempfile
from sample_test_module import TestCondition
object_test_condition = TestCondition()
#pytest.mark.parametrize("test_value",['0'])
def test_condition_pass(test_value):
temp_dir = tempfile.mkdtemp()
temp_src_folder = 'ABC_File'
temp_src_dir = os.path.join(temp_dir , temp_src_folder)
temp_file_name = 'Sample_Test.txt'
temp_file_path = os.path.join(temp_src_dir , temp_file_name)
prev_dir = os.getcwd()
os.chdir(temp_dir)
os.mkdir(temp_src_folder)
try:
with open(temp_file_path , "w") as tmp:
tmp.write("Hello-World\n")
tmp.write("Hi-All\n")
except IOError:
print("Error has occured , please check it.")
org_val = object_test_condition.sample_test(temp_dir)
print("Temp file path is : " + temp_file_path)
print("Temp Dir is : " + temp_dir)
os.chdir(prev_dir)
shutil.rmtree(temp_dir)
print("The respective dir path is now removed.)
assert org_val == test_value
Can you try to close the temp file before removing
temp.close()

Issues reading NetCDF4 LST files from Copernicus

I have a series of hourly LST data from Copernicus. These can be read and displayed fine in Panopoly (Windows version 4.10.6) but:
Crash QGIS 2.18.13 when opening with the 'NetCDF4 Browser' plugin (V0.3)
Reads LST variable incorrectly using R ncdf4 code:
*
file1 <- nc_open('g2_BIOPAR_LST_201901140400_E114.60S35.43E119.09S30.22_GEO_V1.2.nc')
file2 <- nc_open('g2_BIOPAR_LST_201901140500_E114.60S35.43E119.09S30.22_GEO_V1.2.nc')
# attributes(file1)$names
# Just for one variable for now
dat_new <- cbind(
ncvar_get(file1, 'LST'),
ncvar_get(file2, 'LST'))
dim(dat_new)
print(dim(dat_new))
var <- file1$var['LST']$LST
# Create a new file
file_new <- nc_create(
filename = 'Copernicus_LST.nc',
# We need to define the variables here
vars = ncvar_def(
name = 'LST',
units = var$units,
dim = dim(dat_new)))
# And write to it
ncvar_put(
nc = file_new,
varid = 'LST',
vals = dat_new)
# Finally, close the file
nc_close(file_new)
Returns:
[1] "Error, passed variable has a dim that is NOT of class ncdim4!"
[1] "Error occurred when processing dim number 1 of variable LST"
Error in ncvar_def(name = "LST", units = var$units, dim = dim(dat_new)) :
This dim has class: integer
Similarly, using the python netCDF4 approach
compiled = netCDF4.MFDataset(['g2_BIOPAR_LST_201901140400_E114.60S35.43E119.09S30.22_GEO_V1.2.nc','g2_BIOPAR_LST_201901140500_E114.60S35.43E119.09S30.22_GEO_V1.2.nc']))
Returns
ValueError: MFNetCDF4 only works with NETCDF3_* and NETCDF4_CLASSIC formatted files, not NETCDF4
I'm presuming that this is an issue with the file formatting from Copernicus... Has anyone else encountered this? Have put these two example files here.
Thanks!

wxpython can't import files in same directory

I wanted to make a Simple gui with wxpython (In python 3.6.1) because i didn't want to use the commandline for this project anymore.
I have a big file for the Logic in another file, that is also used by other non wxpython files.
But when I try to import my Logic class I Get this error :
ImportError: cannot import name 'QuestionAsk'
I use this Line to import the Logic class :
from Get import QuestionAsk
The file "Get.py" is in the same directory as the gui file.
Here
But it dosen't work why and how can I import this file ?
By the way I call the gui.py file from the get.py file and import the get.py file from the Asker.py file.
ps : Pleas try to not answer :" just copy the content of that class into your gui file" because i use this class elsewhere if there is no other solution then that's ok but that's just ugly and unefficient.
Edit
Here is code from the Get file that starts the Gui :
def graphical_start():
app = wx.App(False) # int app
frame = GuiVocCard() # set frame (GuiVocCard is in the main Gui File)
frame.Show() # show frame
app.MainLoop() # execute loop
And here is The Start of the main Gui class "GuiVocCard" :
class GuiVocCard(wx.Frame):
def __init__(self):
self.language = "es"
self.transList = "C:\\Users\\Justus\\Desktop\\Schule\\spa\VocabGeter\\translations\\big_translation.json"
self.verb_forms = [0,2]
self.High_Score = 0
self.s_file = "scores.json"
self.S_chunk = 40
self.chunk_file = "chunks.json"
self.load_config()
self.q_ask = QuestionAsk(lan=self.language, trans=self.transList, verb_forms=self.verb_forms,
scores_file=self.s_file, chunks_file=self.chunk_file, chunk_size=self.S_chunk)
...
Edit 2 :
The QuestionAsk is defined here in the Get.py file:
class QuestionAsk:
def __init__(self,lan="es",trans="C:\\Users\\Justus\\Desktop\\Schule\\spa\VocabGeter\\translations\\translation.json"
,verb_forms=[0,2],scores_file="scores.json",chunks_file="chunks.json",chunk_size=40):
self.language = lan
self.transList = trans
self.verb_forms = verb_forms
self.High_Score = 0
self.s_file = scores_file
self.S_chunk = chunk_size
self.chunk_file = chunks_file
Fixed it (yay) :
I removed the graphical_start function from the Get.py file and pasted it into the gui.py file . I now import the Gui.py file directly from the Asker.py file .

How to get the default application mapped to a file extention in windows using Python

I would like to query Windows using a file extension as a parameter (e.g. ".jpg") and be returned the path of whatever app windows has configured as the default application for this file type.
Ideally the solution would look something like this:
from stackoverflow import get_default_windows_app
default_app = get_default_windows_app(".jpg")
print(default_app)
"c:\path\to\default\application\application.exe"
I have been investigating the winreg builtin library which holds the registry infomation for windows but I'm having trouble understanding its structure and the documentation is quite complex.
I'm running Windows 10 and Python 3.6.
Does anyone have any ideas to help?
The registry isn't a simple well-structured database. The Windows
shell executor has some pretty complex logic to it. But for the simple cases, this should do the trick:
import shlex
import winreg
def get_default_windows_app(suffix):
class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, suffix)
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
command = winreg.QueryValueEx(key, '')[0]
return shlex.split(command)[0]
>>> get_default_windows_app('.pptx')
'C:\\Program Files\\Microsoft Office 15\\Root\\Office15\\POWERPNT.EXE'
Though some error handling should definitely be added too.
Added some improvements to the nice code by Hetzroni, in order to handle more cases:
import os
import shlex
import winreg
def get_default_windows_app(ext):
try: # UserChoice\ProgId lookup initial
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{}\UserChoice'.format(ext)) as key:
progid = winreg.QueryValueEx(key, 'ProgId')[0]
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Classes\{}\shell\open\command'.format(progid)) as key:
path = winreg.QueryValueEx(key, '')[0]
except: # UserChoice\ProgId not found
try:
class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, ext)
if not class_root: # No reference from ext
class_root = ext # Try direct lookup from ext
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
path = winreg.QueryValueEx(key, '')[0]
except: # Ext not found
path = None
# Path clean up, if any
if path: # Path found
path = os.path.expandvars(path) # Expand env vars, e.g. %SystemRoot% for ext .txt
path = shlex.split(path, posix=False)[0] # posix False for Windows operation
path = path.strip('"') # Strip quotes
# Return
return path

Google Matrix API - python return Nonetype error

"Update"
*Finally resolved the issue, changed the try except to include TypeError and also use pass instead of continue in the except.
"End of update"
I wrote code to search for distance between two locations using Google Distance Matrix API. The origin location are fixed, however for the destination, I get it from an xlsx file. I was expecting to get Dictionary with Destination as the Key and the distance as value. When I run the code below, after certain loop I'm stumbled with this error code:
TypeError: Expected a lat/lng dict or tuple, but got NoneType
Can you help me understand the cause of the error? Here is the code (pygmap.py):
import googlemaps
import openpyxl
#get origin and destination locations
def cleanWB(file_path):
destination = list()
wb = openpyxl.load_workbook(filename=file_path)
ws = wb.get_sheet_by_name('Sheet1')
for i in range(ws.max_row):
cellValueLocation = ws.cell(row=i+2,column=1).value
destination.append(cellValueLocation)
#remove duplicates from destination list
unique_location = list(set(destination))
return unique_location
def getDistance(origin, destination):
#Google distance matrix API key
gmaps = googlemaps.Client(key = 'INSERT API KEY')
distance = gmaps.distance_matrix(origin, destination)
distance_status = distance['rows'][0]['elements'][0]['status']
if distance_status != 'ZERO_RESULTS':
jDistance = distance['rows'][0]['elements'][0]
distance_location = jDistance['distance']['value']
else:
distance_location = 0
return distance_location
And I run it using this code:
import pygmap
unique_location = pygmap.cleanWB('C:/Users/an_id/Documents/location.xlsx')
origin = 'alam sutera'
result = {}
for i in range(len(unique_location)):
try:
result[unique_location[i]] = pygmap.getDistance(origin, unique_location[i])
except (KeyError, TypeError):
pass
If I print results it will show that I have successfully get 46 results
result
{'Pondok Pinang': 25905, 'Jatinegara Kaum': 40453, 'Serdang': 1623167, 'Jatiasih
': 44737, 'Tanah Sereal': 77874, 'Jatikarya': 48399, 'Duri Kepa': 20716, 'Mampan
g Prapatan': 31880, 'Pondok Pucung': 12592, 'Johar Baru': 46791, 'Karet': 26889,
'Bukit Duri': 34039, 'Sukamaju': 55333, 'Pasir Gunung Selatan': 42140, 'Pinangs
ia': 30471, 'Pinang Ranti': 38099, 'Bantar Gebang': 50778, 'Sukabumi Utara': 204
41, 'Kembangan Utara': 17708, 'Kwitang': 25860, 'Kuningan Barat': 31231, 'Cilodo
ng': 58879, 'Pademangan Barat': 32585, 'Kebon Kelapa': 23452, 'Mekar Jaya': 5381
0, 'Kampung Bali': 1188894, 'Pajang': 30008, 'Sukamaju Baru': 53708, 'Benda Baru
': 19965, 'Sukabumi Selatan': 19095, 'Gandaria Utara': 28429, 'Setia Mulya': 635
34, 'Rawajati': 31724, 'Cireundeu': 28220, 'Cimuning': 55712, 'Lebak Bulus': 273
61, 'Kayuringin Jaya': 47560, 'Kedaung Kali Angke': 19171, 'Pagedangan': 16791,
'Karang Anyar': 171165, 'Petukangan Selatan': 18959, 'Rawabadak Selatan': 42765,
'Bojong Sari Baru': 26978, 'Padurenan': 53216, 'Jati Mekar': 2594703, 'Jatirang
ga': 51119}
Resolved the issue to include TypeError in the Try Except. And also use pass instead of continue
import pygmap
unique_location = pygmap.cleanWB('C:/Users/an_id/Documents/location.xlsx')
origin = 'alam sutera'
result = {}
#get getPlace
for i in range(len(unique_location)):
try:
result[unique_location[i]] = pygmap.getDistance(origin, unique_location[i])
except (KeyError, TypeError):
pass
I skipped some locations using this solution though.

Resources