I need to check access to the directory (permissions for groups) on Windows 8.1 / 10. The bottom line is that a situation is possible where all permissions or part of them are prohibited and, in this case, I do not want to throw expection, and even more so with errno.
It is necessary to understand in advance the function (s) that will show whether I will have WinError or PermissionError when reading/writing, for a specific group or all groups (SYSTEM, Administrator, etc.).
The standard stat library and os.access() did not give me the desired results. There are also options with changing permissions for the directory, but this may not always work, especially in usermode, which is why I try to do the verification.
I also tried to read the rights of the ACL, but nothing came of it because of inexperience.
Such conclusions were drawn from the following code (did I check it exactly like that? I don’t know.), And games with the directory security settings (I also changed the location of the directory to the desktop, my documents, %appdata% and other spaces intended for user data [Everything in C:\Users\% USER_NAME%\]. I thought it might be a mistake.), which always produced the same result (maybe sometimes slightly different, but this does not cancel the question).
The most important thing is that an Exception will be thrown if you try to do something with this directory that is not allowed by the rules, and execute in this way:
import os
import stat
def access(path, flag): return os.access(path, flag)
def isExists(path): return access(path, os.F_OK)
def isReadable(path): return access(path, os.R_OK)
def isWritable(path): return access(path, os.W_OK)
def isExecuteable(path): return access(path, os.X_OK)
def mstat(path, followsymlink = 1):
if isinstance(path, str):
info = os.stat(path)
if followsymlink and stat.S_ISLNK(info[stat.ST_MODE]):
return(os.lstat(path))
return(info)
return(os.fstat(path))
def _mode(path): return(mstat(path)[stat.ST_MODE])
def mode(path): return(stat.S_IMODE(_mode(path)))
def ifreg(path): return(stat.S_ISREG(_mode(path)))
def ifdir(path): return(stat.S_ISDIR(_mode(path)))
def ifchr(path): return(stat.S_ISCHR(_mode(path)))
def ifblk(path): return(stat.S_ISBLK(_mode(path)))
def iffifo(path): return(stat.S_ISFIFO(_mode(path)))
def iflnk(path): return(stat.S_ISLNK(_mode(path)))
def ifsock(path): return(stat.S_ISSOCK(_mode(path)))
def is_suid(path): return(_mode(path) & stat.S_ISUID == stat.S_ISUID)
def is_sgid(path): return(_mode(path) & stat.S_ISGID == stat.S_ISGID)
def is_svtx(path): return(_mode(path) & stat.S_ISVTX == stat.S_ISVTX)
def is_read(path): return(_mode(path) & stat.S_IREAD == stat.S_IREAD)
def is_write(path): return(_mode(path) & stat.S_IWRITE == stat.S_IWRITE)
def is_exec(path): return(_mode(path) & stat.S_IEXEC == stat.S_IEXEC)
def is_rwxu(path): return(_mode(path) & stat.S_IRWXU == stat.S_IRWXU)
def is_rusr(path): return(_mode(path) & stat.S_IRUSR == stat.S_IRUSR)
def is_wusr(path): return(_mode(path) & stat.S_IWUSR == stat.S_IWUSR)
def is_xusr(path): return(_mode(path) & stat.S_IXUSR == stat.S_IXUSR)
def is_rwxg(path): return(_mode(path) & stat.S_IRWXG == stat.S_IRWXG)
def is_rgrp(path): return(_mode(path) & stat.S_IRGRP == stat.S_IRGRP)
def is_wgrp(path): return(_mode(path) & stat.S_IWGRP == stat.S_IWGRP)
def is_xgrp(path): return(_mode(path) & stat.S_IXGRP == stat.S_IXGRP)
def is_rwxo(path): return(_mode(path) & stat.S_IRWXO == stat.S_IRWXO)
def is_roth(path): return(_mode(path) & stat.S_IROTH == stat.S_IROTH)
def is_woth(path): return(_mode(path) & stat.S_IWOTH == stat.S_IWOTH)
def is_xoth(path): return(_mode(path) & stat.S_IXOTH == stat.S_IXOTH)
path = 'C:\\ERROR_ACCESS_DENIED_SAMPLE'
print(f'''
mode = {mode(path)}
ifreg = {ifreg(path)}
ifdir = {ifdir(path)}
ifchr = {ifchr(path)}
ifblk = {ifblk(path)}
iffifo = {iffifo(path)}
iflnk = {iflnk(path)}
ifsock = {ifsock(path)}
is_suid = {is_suid(path)}
is_sgid = {is_sgid(path)}
is_svtx = {is_svtx(path)}
is_read = {is_read(path)}
is_write = {is_write(path)}
is_exec = {is_exec(path)}
is_rwxu = {is_rwxu(path)}
is_rusr = {is_rusr(path)}
is_wusr = {is_wusr(path)}
is_xusr = {is_xusr(path)}
is_rwxg = {is_rwxg(path)}
is_rgrp = {is_rgrp(path)}
is_wgrp = {is_wgrp(path)}
is_xgrp = {is_xgrp(path)}
is_rwxo = {is_rwxo(path)}
is_roth = {is_roth(path)}
is_woth = {is_woth(path)}
is_xoth = {is_xoth(path)}
isExists = {isExists(path)}
isReadable = {isReadable(path)}
isWritable = {isWritable(path)}
isExecuteable = {isExecuteable(path)}
''')
Output:
mode = 511
ifreg = False
ifdir = True
ifchr = False
ifblk = False
iffifo = False
iflnk = False
ifsock = False
is_suid = False
is_sgid = False
is_svtx = False
is_read = True
is_write = True
is_exec = True
is_rwxu = True
is_rusr = True
is_wusr = True
is_xusr = True
is_rwxg = True
is_rgrp = True
is_wgrp = True
is_xgrp = True
is_rwxo = True
is_roth = True
is_woth = True
is_xoth = True
isExists = True
isReadable = True
isWritable = True
isExecuteable = True
I would like to see Pure Python as an answer.
the os module does have the os.access function to check access:
os.access('/path/to/folder', os.W_OK) # W_OK is for writing, R_OK for reading, etc.
Related
I'm attempting to develop a registration form, but I can't get the value of the entries because nonetype and return self func are specified.
I tried entering values into the entries, but nothing worked. Again, we find that understanding some of the features and structure of your code is required before you can make modifications.
import tkinter as tk
from tkinter import *
from tkinter import ttk
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
woot = tk.Tk()
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
# SUBMIT Button
submit_button = ttk.Button(tab_2, text="Submit", command=submit).place(x=655,y=700)
App()
Edit: Asked by Delrius Euphoria. The woot = tk.Tk(), app = App(), and woot.mainloop() should be outside of class . ttk.Label should be outside of function
Try this:
import tkinter as tk
from tkinter import *
from tkinter import ttk
woot = tk.Tk()
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
enroll_code =ttk.Entry(woot).place(x=50,y=150)
# SUBMIT Button
submit_button = ttk.Button(woot, text="Submit", command=submit).place(x=655,y=700)
app = App()
woot.mainloop()
I have modified PyModbus Async Asyncio Client Example and created a program (see below) to copy coils and registers from one PLC to another. There is a main thread and a thread for each node(PLC). The modified code works reasonable well. But it turned out that the code runs considerable slower if I configured two pairs of source / destination nodes instead of one pair and copying the same amount of MODBUS packets.
Copying 140 frames from N1 to N2 is way faster (using three thread: main, N1, N2) than copying 70 frames from N1 to N2 and another 70 frames from N3 to N4 (using five threads main, N1, N2, N3, N4)
I expected the configuration with two pairs running faster. What I should change or why my expectation is incorrect? Thanks!
def run_with_already_running_loop(self):
UTILS.LOGGER.info("Running Async client with asyncio loop already started")
UTILS.LOGGER.info("------------------------------------------------------")
def done(future):
UTILS.LOGGER.info("Done !!!")
def start_loop(loop):
"""
Start Loop
:param loop:
:return:
"""
asyncio.set_event_loop(loop)
loop.run_forever()
while True:
for hostdef in self.M_HostList:
if hostdef.host == None or hostdef.host.client.protocol == None:
try:
if hostdef.host == None:
host = COPYHOST()
host.loop = asyncio.new_event_loop()
host.t = Thread(target=start_loop, args=[host.loop])
host.t.daemon = True
# Start the loop
host.t.start()
assert host.loop.is_running()
asyncio.set_event_loop(host.loop)
host.loop, host.client = ModbusClient(schedulers.ASYNC_IO, host=hostdef.IP, port=hostdef.port, loop=host.loop)
hostdef.host = host
host.future = asyncio.run_coroutine_threadsafe(self.start_async_test(hostdef, hostdef.host.client.protocol, hostdef.job, hostdef.time), loop=host.loop)
host.future.add_done_callback(done)
UTILS.LOGGER.info("Made host on {}".format(hostdef.key))
except:
UTILS.LOGGER.info("Failed to make host on {}".format(hostdef.key))
pass
try:
self.manage_jobs(hostdef)
# UTILS.LOGGER.info("### {}".format(hostdef.key))
except:
pass
time.sleep(0.05)
async def start_async_test(self, hostdef, client, job, job_start_time):
last_milli_time = 0
while True:
if client == None:
await asyncio.sleep(1)
continue
current_milli_time = UTILS.UTILS.time_ms()
if job == None:
if (current_milli_time-last_milli_time) > 1000:
#UTILS.LOGGER.info("!!! {}".format(hostdef.key))
last_milli_time = current_milli_time
else:
#UTILS.LOGGER.info("!!! {} {}".format(hostdef.key, job.state))
pass
if job != None and job.state == 3 and hostdef.oqueue.qsize() == 0:
assert job_start_time != 0
job.state = 4
#UTILS.LOGGER.info("FINISHING JOB: {}".format(job.SD.key))
fjob = deepcopy(job)
hostdef.oqueue.put(fjob)
job = None
job_start_time = 0
if job == None and hostdef.iqueue.qsize() != 0:
job = hostdef.iqueue.get()
job.state = 1
job_start_time = current_milli_time
#UTILS.LOGGER.info("START JOB: {}".format(job.SD.key))
if job != None and job.dir == 'D' and job.state == 1:
# in case of destination we write
job.state = 2
if job.SD.type == '%M':
rq = await client.write_coils(job.SD.start, job.buffer, unit=UNIT)
job.state = 3
if rq.function_code < 0x80:
job.Fault = False
else:
job.Fault = True
assert False
pass
elif job.SD.type == '%MW':
rq = await client.write_registers(job.SD.start, job.buffer, unit=UNIT)
job.state = 3
if rq.function_code < 0x80:
job.Fault = False
else:
job.Fault = True
assert False
pass
else:
assert False
elif job != None and job.dir == 'S' and job.state == 1:
# in case of source we read
job.state = 2
if job.SD.type == '%M':
rr = await client.read_coils(job.SD.start, job.SD.size, unit=UNIT)
job.state = 3
if rr.function_code < 0x80:
job.Fault = False
job.buffer = rr.bits
else:
job.Fault = True
job.buffer = None
assert False
pass
elif job.SD.type == '%MW':
rr = await client.read_holding_registers(job.SD.start, job.SD.size, unit=UNIT)
job.state = 3
if rr.function_code < 0x80:
job.Fault = False
job.buffer = rr.registers
else:
job.Fault = True
job.buffer = None
assert False
else:
assert False
await asyncio.sleep(0.01)
I have created a Tree object with the following structure:
class Tree:
def __init__(self, data=None):
self.data = data
self.left_child = None
self.right_child = None
An instance of this object is:
tree = Tree("A")
tree.left_child = Tree("B")
tree.right_child = Tree("C")
tree.left_child.left_child = Tree("D")
tree.left_child.right_child = Tree("E")
tree.right_child.left_child = Tree("F")
tree.right_child.right_child = Tree("G")
Its Newick format should be ((G,F)C,(E,D)B)A;
How can I convert any instance of Tree object to its Newick format?
Thanks to Blckknght for his hint.
def to_newick(tree):
newick = ""
newick = traverse(tree, newick)
newick = f"{newick};"
return newick
def traverse(tree, newick):
if tree.left_child and not tree.right_child:
newick = f"(,{traverse(tree.left_child, newick)}){tree.data}"
elif not tree.left_child and tree.right_child:
newick = f"({traverse(tree.right_child, newick)},){tree.data}"
elif tree.left_child and tree.right_child:
newick = f"({traverse(tree.right_child, newick)},{traverse(tree.left_child, newick)}){tree.data}"
elif not tree.left_child and not tree.right_child:
newick = f"{tree.data}"
else:
pass
return newick
I just thought you might want something not recursive, iterative implementations usually run faster.
from typing import List
class Tree:
def __init__(self, data=None):
self.data: str = data
self.left_child: Tree = None
self.right_child: Tree = None
def newick(self) -> str:
# Recursive version
# Practically a postorder tree traversal
if not self.left_child and not self.right_child:
return self.data
left_child = self.left_child.newick() if self.left_child else ""
right_child = self.right_child.newick() if self.right_child else ""
return f"({right_child},{left_child}){self.data}"
def newick_iter(self) -> str:
# Iterative version
# https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/
res: str = ""
traverse_stack: List[Tree] = []
curr: Tree = self
while True:
while curr:
if curr.left_child:
traverse_stack.append(curr.left_child)
res += '('
traverse_stack.append(curr)
curr = curr.right_child
curr = traverse_stack.pop()
if curr.left_child and (traverse_stack and curr.left_child == traverse_stack[-1]):
tmp = traverse_stack.pop()
traverse_stack.append(curr)
curr = tmp
if res[-1] == ')':
res = res[:-1]
res += ','
else:
res += curr.data + ')'
curr = None
if not traverse_stack:
break
res = res[:-1]
return res
def main():
tree = Tree("A")
tree.left_child = Tree("B")
tree.right_child = Tree("C")
tree.left_child.left_child = Tree("D")
tree.left_child.right_child = Tree("E")
tree.right_child.left_child = Tree("F")
tree.right_child.right_child = Tree("G")
print(tree.newick_iter())
print(tree.newick())
if __name__ == '__main__':
main()
Here is the code
import random
class Animal(object):
__name = ""
__animal_type = ""
__mood = 0
def __init__(self, animal_type, animal_name):
self.__animal_type = animal_type
self.__name = animal_name
self.__mood = random.randint(1, 3)
def get_animal_type(self, animal):
return self.__animal_type
def get_name(self, animal):
return self.__name
def check_mood(self, animal):
animal_mood = ""
if self.__mood == 0:
animal_mood = "the mood was 0 and didn't change"
elif self.__mood == 1:
animal_mood = "happy"
elif self.__mood == 2:
animal_mood = "hungry"
elif self.__mood == 3:
animal_mood = "sleepy"
return animal_mood
animal_list = [Animal]
do_animal_creation = True
while do_animal_creation:
print("Welcome to animal gen")
new_animal_type = input("What type of animal? ")
new_animal_name = input("Name of animal? ")
new_animal = Animal(new_animal_type, new_animal_name)
animal_list.append(new_animal)
do_animal_creation = input("Add another animal? y/n: ")
if do_animal_creation != 'y':
do_animal_creation = False
print("\nThanks for using this program.")
else:
do_animal_creation = True
print("Animal list:")
for item in animal_list:
item_name = item.get_name(item)
item_type = item.get_animal_type(item)
item_mood = item.check_mood(item)
print(item_name + " the " + item_type + " is " + item_mood + ".")
Everytime I try to call the get_name or get_animal_type or check_mood methods it tells me I'm sending an incorrect amount of parameters. Then I try to play with the parameters, either send one more like it asks me to, or take away a parameter in the method definition within the class, and neither of those work. I feel like I am syntactically not calling the methods correctly, but I don't know what exactly I'm doing wrong.
The first element of your animal_list is the Animal class, not an instance. Hence, calling instance methods on it won't work as expected. Whatever you might have tried to make that work (like passing an instance as first argument) will then fail for the subsequent elements which are instances.
Change
animal_list = [Animal]
# this puts the Animal class in your list
# Note: In Python, lists are not type-parametrized like in other languages,
# which is probably what you assumed you were doing
to
animal_list = []
Moreover, your getters should not take parameters:
def get_animal_type(self):
return self.__animal_type
and call it:
item.get_animal_type()
#pytest.mark.usefixtures("oneTimeSetup","setUp")
class SignUpFLow2(unittest.TestCase):
print("running once")#pytest.fixture(autouse=True)
def classSetup(self,oneTimeSetup):
print("running twice")
self.nhp = Noon_home_page(self.driver)
self.nrp = Noon_Regional_Page(self.driver)
self.nsas = Noon_signup_Page(self.driver)
self.nso = Noon_Sign_Out(self.driver)
self.nsi = Noon_SignIn(self.driver)
self.xl = xcelReading()
xlw = write_to_excel()
xl1 = xlsReadingvig()
path = xlw.writing()
print(path)
column_length = xl1.columnCount()
print(column_length)
for i in range(0, column_length):
self.cell_value1 = xl1.excel(0, i, path)
self.cell_value2 = xl1.excel(0, i + 1, path)
self.cell_value3 = xl1.excel(0, i + 2, path)
break
self.value1 = self.cell_value1
self.value2 = self.cell_value2
self.value3 = self.cell_value3#pytest.mark.run(order=1)
def test2(self):
print("first test running")
result = self.nhp.verifyLoginSuccessfull()
self.nhp.Click()
time.sleep(2)
self.nhp.ClickLanguage()
assert result == True # asserting noon icon on home page
#pytest.mark.run(order=2)
def test3(self):
print("Second test running")
self.nrp.Click()
time.sleep(2)
result1 = self.nrp.verifyTitle()
self.nrp.SignUpClick()
assert result1 == True # asserting page title