Recommand · May 26, 2021 0

Run an OS command as administrator in python

This question already has an answer here:

How to run cmd command in Python with admin

(1 answer)

Closed 2 hours ago.

I am trying to use the os module in python to remove a folder, but I keep getting PermissionError: [WinError 5] Access is denied. I have heard of a module called admin, but whenever I try this, it seems as if all the functions being called with it were not in the __init__().

My Code:

import os
os.remove("directory (not actually what I am trying to delete)")

In the comments, you suggested the linked answer doesn’t work, but:

C:\temp>virtualenv quick
created virtual environment in 2262ms
  creator CPython3Windows(dest=C:\temp\quick, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\grism\AppData\Local\pypa\virtualenv)
    added seed packages: pip==21.0.1, setuptools==56.0.0, wheel==0.36.2
  activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

C:\temp>cd quick


(quick) C:\temp\quick>pip install pywin32
Collecting pywin32
  Using cached pywin32-300-cp39-cp39-win_amd64.whl (9.2 MB)
Installing collected packages: pywin32
Successfully installed pywin32-300
WARNING: You are using pip version 21.0.1; however, version 21.1.2 is available.
You should consider upgrading via the 'C:\temp\quick\Scripts\python.exe -m pip install --upgrade pip' command.

(quick) C:\temp\quick>python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import as shell
<module '' from 'C:\\temp\\quick\\lib\\site-packages\\win32comext\\shell\\shell.pyd'>

So it must be some other problem on your end.