0

i am trying to remove the folder variable "name" if its been in the folder longer than X amount of time. Can i run this script in admin mode without having to "right click" and run as admin? If i try to automate this script i would need something to that nature. I try using the os.remove function but i get an error below:

Error

PermissionError: [WinError 5] Access is denied:

Code:

for root, folders, files in os.walk('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof'):
for name in folders:
    datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
    filedate = str(datetime.fromtimestamp(os.path.getmtime(os.path.join(root, name))))
    now_time = str(datetime.now())
    now_time = datetime.strptime(now_time, datetimeFormat)
    filetime = datetime.strptime(filedate, datetimeFormat)
    difference = now_time-filetime
    if difference > timedelta(days=2):
        print(filetime)
        print(difference)
        print('Hi')
        # os.remove('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\' + name)
        shutil.rmtree('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\' + name)
        file_times = os.path.join("\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\", name), ": ", str(
            difference)
        file_times_final.append(file_times[0] + file_times[1] + file_times[2])
    else:
        print("None")
        break

1 Answers1

0

Assuming the issue is that Python is not elevated, the solution provided here might be useful.

To run an external command from within Python, this solution could be suitable:

#!python
# coding: utf-8
import sys
import ctypes

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True

    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print 'Command line: ', executable, argument_line
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None


if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print 'I have admin privilege.'
        raw_input('Press ENTER to exit.')
    elif ret is None:
        print 'I am elevating to admin privilege.'
        raw_input('Press ENTER to exit.')
    else:
        print 'Error(ret=%d): cannot elevate privilege.' % (ret, )

The key lines seem to be

import ctypes
shell32 = ctypes.windll.shell32
shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
Eran Raveh
  • 31
  • 3