This is Python code for website blocking. I am using Jupyter notebook to run this code. When I run this program I am getting error name as PermissionError.
import datetime
import time
end_time=datetime.datetime(2022,9,22)
site_block=["www.wscubetech.com","www.facebook.com"]
host_path="C:/Windows/System32/drivers/etc/hosts"
redirect="127.0.0.1"
while True:
if datetime.datetime.now()<end_time:
print("Start Blocking..")
with open(host_path,"r+") as host_file:
content = host_file.read()
for website in site_block:
if website not in content:
host_file.write(redirect+" "+website+"\n")
else:
pass
else:
with open(host_path,"r+") as host_file:
content = host_file.readlines()
host_file.seek(0)
for lines in content:
if not any(website in lines for website in site_block):
host_file.write(lines)
host_file.truncate()
time.sleep(5)
This is the error I get when I run this program:
PermissionError
Traceback (most recent call last)
Input In [15], in <cell line: 8>()
9 if datetime.datetime.now()<end_time:
10 print("Start Blocking..")
---> 11 with open(host_path,"r+") as host_file:
12 content = host_file.read()
13 for website in site_block:
PermissionError: [Errno 13] Permission denied: 'C:/Windows/System32/drivers/etc/hosts
Permission denied simply means the system is not having permission to open the file to that folder.
C:\Windows\System32\drivers\etc\hosts is writable only by the Administrator. You should run your script in Administrator mode.
EDIT (23/09/2022 - comment):
I ran your code with pycharm in administrator mode, no error and no output but the file was modified (two extra lines then deleted):
I rewrote the code for testing. Here it is for a different approach:
site_block = ["www.facebook.com", "www.stackoverflow.com"]
host_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
with open(host_path, "r+") as host_file:
for website in filter(lambda website: website not in host_file.read(), site_block):
host_file.write(redirect + " " + website + "\n")
time.sleep(5)
with open(host_path, "r") as host_file:
lines = host_file.readlines()
with open(host_path, "w") as output:
for line in lines:
if not any(redirect + " " + website + "\n" == line for website in site_block):
output.write(line)
Tips:
You can use a boolean to know if you have already updated the file to avoid opening it every 5 seconds.
You can stop the process after cleaning the file.
You can also look to run the code with a cron.
The PermissionError is caused when you do not have a permission to do something.
The file C:/Windows/System32/drivers/etc/hosts is protected by the permission. That is why you cannot access to it.
Why don't you run it as administrator?
Related
So I am trying to code a website blocker. When I finished the code, I get a permission error. I am using a Windows computer. Can you please tell me what I am doing wrong or help fix my problem? Thank you in advance.
import time
from datetime import datetime as dt
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
website_list = ["https://www.youtube.com/", "youtube.com"]
final_list = [redirect + " "+ i for i in website_list]
final_string_block = "\n".join(final_list)
while True:
if dt(dt.now().year, dt.now().month, dt.now().day, 8,) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,18):
print("Within Time...")
with open(hosts_path, "r+") as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
file.write(redirect+ ""+website+"\n")
else:
with open(hosts_path, "r+") as file:
content = file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in website_list):
file.write(line)
file.truncate()
time.sleep(5)
This is the error:
Traceback (most recent call last):
File "c:\Users\chris\.vscode\Realistic Programs\tempCodeRunnerFile.python", line 13, in <module>
with open(hosts_path, "r+") as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\drivers\\etc\\hosts'
Because the hosts file is applicable to all users you need administrative privileges to write to it. Try running python as administrator and you should be able to edit the file.
I'm trying to upload some files to Dropbox using Python and the Dropbox api.
This is what I have so far -
import sys
import dropbox
import time
from dropbox.files import WriteMode
from dropbox.exceptions import ApiError, AuthError
# Access dropboxToken
dropboxToken = '<token>'
localPath = '<local path in Downloads folder>'
uploadPath = '<dropbox path>'
# Uploads contents of localFile to Dropbox
def upload():
with open(localPath, 'rb') as f:
for file in localPath:
# We use WriteMode=overwrite to make sure that the settings in the file
# are changed on upload
print('Uploading ' + localFile + ' to Dropbox location ' + uploadPath)
try:
dbx.files_upload(f.read(), uploadPath, mode=WriteMode('overwrite'))
except ApiError as err:
# This checks for the specific error where a user doesn't have enough Dropbox space quota to upload this file
if (err.error.is_path() and
err.error.get_path().error.is_insufficient_space()):
sys.exit('ERROR: Cannot upload file; insufficient space.')
elif err.user_message_text:
print(err.user_message_text)
sys.exit()
else:
print(err)
sys.exit()
if __name__ == '__main__':
print('Uploading file(s)...')
# upload the files
upload()
Whenever I run it I receive the following message: PermissionError: [Errno 13] Permission denied
I've read some other threads about running IDLE as admin, executing the file from the command line as admin, checking the permissions of the file path, etc. but none of those suggestions are working. Is there something wrong with my code, or something else I'm not thinking of?
I'm on Windows 10 and my account is a local administrator, and I'm using Python 3.8.1. Any help is greatly appreciated.
I am trying to open a JSON file.
Here is my code:
import json
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
data = json.loads(fh)
for i in data:
print(i)
However, I keep getting the error:
Traceback (most recent call last):
File "C:\Users\Joker\Desktop\Python\jsondatabase.py", line 3, in <module>
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
PermissionError: [Errno 13] Permission denied: 'C:/Users/Joker/Desktop/Python/Code3/roster'
[Finished in 0.135s]
How can I access the data?
Edit: It worked when I ran as admin. Thanks everyone!
The code as written orphans the file handler, leaving it open. It may very well be open in another program which is hard to see from the process manager, but you should edit to:
import json
with open('C:/Users/Joker/Desktop/Python/Code3/roster.json', "r") as fh:
data = json.load(fh)
for i in data:
print(i)
To clear the orphaned handler you could try wack-a-mole with the task manager or just restart your machine.
I'm trying to scrape some information and then add it to a text file but when I run the script, I get the following error:
PermissionError: [Errno 13] Permission denied: 'stocks.txt'
I'm doing this for adding to the file.
f = open("stocks.txt", "a")
f.write(containers[0].string + "\n")
f.close()
When I go to my file explorer and right click the program and press run, it prints to the file but any other way gives me the error.
I have a python script which polls a folder to see if a new file is added, and when a new file is added, it loads the text file into numpy.
before = dict([(f, None) for f in os.listdir('.')])
while 1:
#time.sleep(10)
after = dict([(f, None) for f in os.listdir('.')])
added = [f for f in after if f not in before]
if added:
print added[0]
try:
raw = numpy.loadtxt(added[0])
except IOError:
print "----- Error"
core.wait(0.1)
raw = numpy.loadtxt(added[0])
When I don't try catching the exception, I get an error in reading the file - "Permission denied". I am a Windows administrator, so this should not be an issue. It also only happens on some files, so I think the script might be trying to open the file before it is fully written. Is there any way to get rid of this error?