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
Related
Its supposed to whire whatever is in my clipboard to a file and stop when pressing control + shift + p that part works but the getting clipboard doesnt.
Heres my code
import win32clipboard
import keyboard
filename = input("Filename: ")
file = open(filename, "a")
data = ""
while True:
previousdata = data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print(data)
if data != previousdata:
file.write(data+"\n")
else:
print("No change")
if keyboard.is_pressed("ctrl+shift+p"):
break
print("Stopped")
import os
os.system("pause")
And here is the error message
Traceback (most recent call last):
File "C:\Users\Juli\Desktop\python\clipboardcopy.py", line 8, in <module>
win32clipboard.OpenClipboard()
pywintypes.error: (5, 'OpenClipboard', 'Access denied.')
Seems like PyWin32 has an issue with the clipboard getting locked by other processes, resulting in an "Access is Denied" message.
Try calling the API directly using ctypes. As a bonus your code will also not rely on a 3rd party packages that's not included with the interpreter.
Here's an example:
https://stackoverflow.com/questions/101128/how-do-i-read-text-from-the-clipboard/23285159#23285159
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 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).
I'm trying to create and write a file if it does not exist yet, so that it is co-operatively safe from race conditions, and I'm having (probably stupid) problem. First, here's code:
import os
def safewrite(text, filename):
print "Going to open", filename
fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666) ##### problem line?
print "Going to write after opening fd", fd
os.write(fd, text)
print "Going to close after writing", text
os.close(fd)
print "Going to return after closing"
#test code to verify file writing works otherwise
f = open("foo2.txt", "w")
f.write("foo\n");
f.close()
f = open("foo2.txt", "r")
print "First write contents:", f.read()
f.close()
os.remove("foo2.txt")
#call the problem method
safewrite ("test\n", "foo2.txt")
Then the problem, I get exception:
First write contents: foo
Going to open foo2.txt
Going to write after opening fd 5
Traceback (most recent call last):
File "/home/user/test.py", line 21, in <module>
safewrite ("test\n", "foo2.txt")
File "/home/user/test.py", line 7, in safewrite
os.write(fd, text)
OSError: [Errno 9] Bad file descriptor
Probable problem line is marked in the code above (I mean, what else could it be?), but I can't figure out how to fix it. What is the problem?
Note: above was tested in a Linux VM, with Python 2.7.3. If you try the code and it works for you, please write a comment with your environment.
Alternative code to do the same thing at least as safely is also very welcome.
Change the line:
fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666)
to be instead:
fd=os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)
You must open the file with a flag such that you can write to it (os.O_WRONLY).
From open(2):
DESCRIPTION
The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only,
write-only, or read/write, respectively.
From write(2):
NAME
write - write to a file descriptor
...
ERRORS
EAGAIN The file descriptor fd has been marked non-blocking (O_NONBLOCK) and the write would block.
EBADF fd is not a valid file descriptor or is not open for writing.
I am trying to upload a file to an ftp server with python using the ftplib.
This is what i have:
def ftp(cmd):
cmd = cmd.split(' ')
try: cmd[3]
except: return 'host user password file (ftpdir)'
try: session = ftplib.FTP(cmd[0],cmd[1],cmd[2])
except: return 'wrong credentials/host'
try: file = open(cmd[3], 'rb')
except: return 'unable to reach file'
try: cmd[4]
except: pass
else:
if cmd[4] !='':
ftplib.FTP.cwd(ftpdir)
name = file.split('\\')[-1]
session.storbinary('STOR ' + name, file) # send the file
file.close() # close file and FTP
session.quit()
I give the function a command in the form of 'host user password file ftpdir' where ftpdir is not required. The error I get is this one:
Traceback (most recent call last):
...some lines of referring...
File "C:\somedir\somefile.py", line 155, in ftp
file = open(cmd[3],'rb')
TypeError: open() takes exactly 1 argument (2 given)
If i try the command "file = open(cmd[3], 'rb')" with a given 'cmd' as entry in a python shell it works fine.
This question is now answered. The problem was that I defined another function open(arg) which took exactely one argument. After changing the name of that function, everything worked fine.
Thank you for your time everyone who read this.