I have the following code:
#!/usr/bin/python
export = open('/sys/class/gpio/export', 'w')
export.write('44\n')
And this code produces the following output:
close failed in file object destructor:
IOError: [Errno 16] Device or resource busy
If I change the code by adding a export.close() to the end, I get this as output:
Traceback (most recent call last):
File "./test.py", line 5, in <module>
export.close()
IOError: [Errno 16] Device or resource busy
However, if I change the code again as such, it works perfectly:
#!/usr/bin/python
from time import sleep
export = open('/sys/class/gpio/export', 'w')
sleep(1)
export.write('44\n')
Note that .close ALWAYS fails, even if I put a long sleep after the write.
Edit:
Changed my code to be the following:
with open('/sys/class/gpio/export', 'w') as export:
sleep(1)
export.write('44\n')
export.flush()
export.close()
Still gives errors:
Traceback (most recent call last):
File "./test.py", line 7, in <module>
export.flush()
IOError: [Errno 16] Device or resource busy
Edit 2:
My main issue turned out to be that you can't export a GPIO that has already been exported. I've updated my code to look like this and it seems to be working:
from os import path
if not path.isdir('/sys/class/gpio/gpio44'):
with open('/sys/class/gpio/export', 'w') as export:
export.write('44\n')
if path.exists('/sys/class/gpio/gpio44/direction'):
with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
gpio44_dir.write('out\n')
if path.exists('/sys/class/gpio/gpio44/value'):
with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
gpio44_val.write('1\n')
This code successfully exports a GPIO, sets its direction to "out", and actives it (value to 1).
My main issue turned out to be that you can't export a GPIO that has already been exported. I've updated my code to look like this and it seems to be working:
from os import path
if not path.isdir('/sys/class/gpio/gpio44'):
with open('/sys/class/gpio/export', 'w') as export:
export.write('44\n')
if path.exists('/sys/class/gpio/gpio44/direction'):
with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
gpio44_dir.write('out\n')
if path.exists('/sys/class/gpio/gpio44/value'):
with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
gpio44_val.write('1\n')
This code successfully exports a GPIO, sets its direction to "out", and actives it (value to 1).
Related
I'm trying to send commands to Audacity using a named pipe, which can be tested using: (https://github.com/audacity/audacity/blob/master/scripts/piped-work/pipe_test.py provided by Audacity)
import os
import sys
if sys.platform == 'win32':
print("pipe-test.py, running on windows")
TONAME = '\\\\.\\pipe\\ToSrvPipe'
FROMNAME = '\\\\.\\pipe\\FromSrvPipe'
EOL = '\r\n\0'
else:
print("pipe-test.py, running on linux or mac")
TONAME = '/tmp/audacity_script_pipe.to.' + str(os.getuid())
FROMNAME = '/tmp/audacity_script_pipe.from.' + str(os.getuid())
EOL = '\n'
print("Write to \"" + TONAME +"\"")
if not os.path.exists(TONAME):
print(" ..does not exist. Ensure Audacity is running with mod-script-pipe.")
sys.exit()
print("Read from \"" + FROMNAME +"\"")
if not os.path.exists(FROMNAME):
print(" ..does not exist. Ensure Audacity is running with mod-script-pipe.")
sys.exit()
print("-- Both pipes exist. Good.")
TOFILE = open(TONAME, 'w')
print("-- File to write to has been opened")
FROMFILE = open(FROMNAME, 'rt')
print("-- File to read from has now been opened too\r\n")
On a first run, with Audacity open, this yields:
pipe-test.py, running on windows
Traceback (most recent call last):
Write to "\\.\pipe\ToSrvPipe"
Read from "\\.\pipe\FromSrvPipe"
File "C:/Users/chris/PycharmProjects/Youtube-Spotify-DL/pipe_test3.py", line 44, in <module>
-- Both pipes exist. Good.
TOFILE = open(TONAME, 'w')
OSError: [Errno 22] Invalid argument: '\\\\.\\pipe\\ToSrvPipe'
Process finished with exit code 1
On a second run:
Traceback (most recent call last):
File "C:/Users/chris/PycharmProjects/Youtube-Spotify-DL/pipe_test3.py", line 44, in <module>
pipe-test.py, running on windows
TOFILE = open(TONAME, 'w')
FileNotFoundError: [Errno 2] No such file or directory: '\\\\.\\pipe\\ToSrvPipe'
Write to "\\.\pipe\ToSrvPipe"
Read from "\\.\pipe\FromSrvPipe"
-- Both pipes exist. Good.
Process finished with exit code 1
So it seems like the pipe cannot be written to and/or closes. However, when running this script through IDLE, it runs just fine. So, in what way is Pycharm preventing writing to this named pipe, and how could it be fixed?
Thanks.
Did you open audacity before running the test script? Audacity needs to run
so I have a problem trying to run this python code as administrator so I am not able to access and write on host file. Can anyone help me? I have looked through many of other questions but non of them seem to work.
Host File Directory: C:\Windows\System32\Drivers\etc\hosts
(Such as)
Request UAC elevation from within a Python script?
Some of these answers actually work on prompting to get administrator access, but it still doesn't give permission to my program. The only way I figured out is to run python shell as administrator first and then run the code or run the command prompt as administrator and open python file with command prompt.
WEBSITE
https://boostlog.io/#faisalnad/create-a-website-blocker-with-python-5afe86ff47018500491f4898
This program is made for blocking website.
import time
from datetime import datetime as dt
# change hosts path according to your OS
hosts_path = r”C:\Windows\System32\Drivers\etc\hosts”
# localhost's IP
redirect = "127.0.0.1"
# websites That you want to block
website_list = ["www.facebook.com","facebook.com",
"dub119.mail.live.com","www.dub119.mail.live.com",
"www.gmail.com","gmail.com"]
while True:
# time of your work
if dt(dt.now().year, dt.now().month, dt.now().day,8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,16):
print("Working hours...")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
# mapping hostnames to your localhost IP address
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)
# removing hostnmes from host file
file.truncate()
print("Fun hours...")
time.sleep(5)
This is the error:
Working hours...
Traceback (most recent call last):
File "C:\Users\Key\Desktop\random project.py", line 19, in <module>
with open(hosts_path, 'r+') as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\Drivers\\etc\\hosts'
FILE DIRECTORY
You can add write permission for the user under which your program runs following this link to add permission to the host file
I am observing a "Bad address" OSError when reading from a file handle created using the with syntax in Python 3.
The file in question is 39G, but I should have enough RAM available to read the whole file. The error message leads me to believe I am hitting some kind of OS restriction; I am running CentOS 6.9. Can anyone help me understand what might be causing this behavior?
The file is perfectly readable outside of python, e.g. in bash with head or vim.
Simplified code sample producing the error is shown below:
In [2]: with open(filename, 'r', encoding="utf8") as infile:
...: infile.read()
...:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-2-3f216811bec7> in <module>()
1 with open(filename, 'r', encoding="utf8") as infile:
----> 2 infile.read()
3
OSError: [Errno 14] Bad address
I am trying to build a program that reads a value from a separate text file. In this case, it is named "Test.lang". It contains the text "Hello World".
My program was working just fine with:
from sys import *
def open_file(filename):
print (filename)
def run():
data = open_file(argv[1])
run()
Then, when I tried to change it to:
from sys import *
def open_file(filename):
data = open(filename, "r").read()
print (data)
def run():
data = open_file(argv[1])
run()
It does not work. I get 4 errors:
Traceback (most recent call last):
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 10, in <module>
run()
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 8, in run
data = open_file(argv[1])
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 4, in open_file
data = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'test.lang'
What is really confusing me is the last one. How did the previous program work, but now test.lang doesn't exist?
Please help me.
Here is how you do this.
To read a file:
file = open('Directory Of The File.txt', 'r')
MyVariable = file.read()
file.close()
To write a file:
file = open('Directory Of The File.txt', 'w')
file.write('Insert Text, Variable or Other Data Here!')
file.close()
It's as easy as that!
You can change the .txt for .lang or any other supported file extension!
Please reply and let me know if this worked for you :)
I am very new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting (I have even looked at similar threads on S.O.) but can't get past my issue.
I'm not sure if I have to redirect or create a directory, and I'm not sure how I'd do so.
Here is my code:
try:
import json, time, os, re, StringIO
from PIL import Image
from urllib import urlencode
import requests, base58
from BeautifulSoup import BeautifulSoup
except:
print('ERROR:: missing module(s)')
exit()
settings = json.loads(open('./settings/settings', 'r').read())
login = open('./settings/login', 'r').read().splitlines()
sessions = []
loginIndex = 0
and here is the error I am receiving:
> Traceback (most recent call last): File
> "C:\Users\Administrator\Desktop\api\main.py", line 19, in
> <module>
> settings = json.loads(open('./settings/settings', 'r').read()) IOError: [Errno 2] No such file or directory: './settings/settings'
What is causing the IOError and how to I resolve it?