Having problems finding how to add songs to playlist on Raspberry PI (Jessie Lite)
When I am trying to add file, either giving directory name or file it says :
mpd.base.CommandError: [50#0] {add} Not found
or "bad URI"
I changed the music directory in mpd.conf to home directory but it didn't help. Can i change MPD music directory from Python?
from mpd import MPDClient
client = MPDClient()
client.connect("localhost", 6600)
client.update()
//client.add("music/")
client.add("file.mp3")
Aim is just to manage playlist, create and remove songs on demand with python
Answer was found here https://stackoverflow.com/a/37632225/2838794
sudo nano /etc/mpd.conf
Inside file:
bind_to_address "/run/mpd/socket"
After saving the file
export MPD_HOST=/run/mpd/socket
systemctl restart mpd
Related
When I run this os.walk code from my PyScripter IDE, it works just fine. The os.walk was able to traverse the remote unix path and print the directory and file names.
However, when I run this same script from the cgi-bin of my Apache server, I get no os.walk (path, dirs, files) output. I also don't get any error messages recorded in the Apache error.log file.
Note: Python and my cgi-bin are on the same Windows machine, and the remote_path is on Unix.
Why does this same code work from the console but not from the cgi-bin and what can I do to resolve this?
#!C:\Python27\python.exe -u
import os
print "Content-type: text/html\n\n";
print "<html><head>"
print "<font size=+2><B>os.walk test</B></font><br><br>";
# Remote path
remote_path = r'\\unix_server\path\2015\q1\files\na\canada'
i = 0
for (path, dirs, files) in os.walk(remote_path):
print "Path", path
print "<BR><BR>Dirs", dirs
print "<BR><BR>Files", files
i += 1
if i >= 1:
break
Thanks to kindall, I found out the problem was indeed that Apache didn't have the appropriate permissions.
To solve the issue, I did the following (Windows 7 OS):
Opened services.msc. Start -> Run -> "services.msc"
Located my Apache service in the list "Apache2". Double click it.
In the Properties dialog for the Apache2 service, switch to the "Log On" tab. The radio button for "Local System account" was checked. I switched it to "This account" and clicked Browse.
In the "Enter object name to select" text box, I entered the name of my network + backslash + my user name. For example NETWORK\username. Clicked OK.
Then on the Log On tab, I saw that my full network email address was populated. I entered my password and password confirmation and clicked Apply.
The final steps were to stop the Apache2 service and then restart the service. Once that was done, the problem was solved and my script started working from the cgi-bin. :)
I'm trying to find out wether a mediafile "could" be played back in VLC using LibVLC-Python.
In my python script I parse recursively through a directory (containing media and non-media-files as well as images etc.), opening and playing one file after another in VLC. Then I try to analyse, if it can actually be played with the vlc-functions will_play() and get_state(). This is highly unreliable though and the script has to pause in order to fully load the file. If an audio-file for example is very short and the script pauses to long it will not be detected as "playable" since it's playback has already stopped etc. If the script runs across a JPG it hangs up and sometimes text- and pdf-files will be labeled "will_play" :-( So far I was not able to use vlc-classes such as MediaTrackInfo()
Is there a way to just parse each file and determine i.e. by it's codec if VLC could play it? I just want to sort through huge directories and copy out "real" mediafiles (audio and video) that are not corrupted.
Here's my original script:
import os, sys, inspect, time
vlcpfad = "C:\Program Files (x86)\VideoLAN\VLC"
if not vlcpfad in sys.path:
sys.path.append(vlcpfad)
import vlc
# Get name and path of the script
pfadkomplett = os.path.realpath(os.path.abspath(inspect.getfile(inspect.currentframe())))
pfad = os.path.split(pfadkomplett)[0]
skriptname = os.path.split(pfadkomplett)[1]
# walk path
for pfad, unterordner, dateien in os.walk(pfad):
for dateiname in dateien:
# skip script itself
if dateiname == skriptname: continue
dateipfad = os.path.join(pfad, dateiname)
p = vlc.MediaPlayer(dateipfad)
p.audio_toggle_mute()
p.play()
# Wait a bit, so vlc can start playback
time.sleep(0.2)
while str(p.get_state()) == "State.Opening":
time.sleep(0.1)
print(dateipfad + ": " + str(p.will_play()))
p.stop()
del p
One way is to test if media is OK before play it :
[...]
p = vlc.MediaPlayer(dateipfad)
media = p.get_media()
media.parse() #get media info
if media.get_duration():
# your is OK
else:
# media NOK
Original Question
I've got some python scripts which have been using Amazon S3 to upload screenshots taken following Selenium tests within the script.
Now we're moving from S3 to use GitHub so I've found GitPython but can't see how you use it to actually commit to the local repo and push to the server.
My script builds a directory structure similar to \images\228M\View_Use_Case\1.png in the workspace and when uploading to S3 it was a simple process;
for root, dirs, files in os.walk(imagesPath):
for name in files:
filename = os.path.join(root, name)
k = bucket.new_key('{0}/{1}/{2}'.format(revisionNumber, images_process, name)) # returns a new key object
k.set_contents_from_filename(filename, policy='public-read') # opens local file buffers to key on S3
k.set_metadata('Content-Type', 'image/png')
Is there something similar for this or is there something as simple as a bash type git add images command in GitPython that I've completely missed?
Updated with Fabric
So I've installed Fabric on kracekumar's recommendation but I can't find docs on how to define the (GitHub) hosts.
My script is pretty simple to just try and get the upload to work;
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
import os
def git_server():
env.hosts = ['github.com']
env.user = 'git'
env.passowrd = 'password'
def test():
process = 'View Employee'
os.chdir('\Work\BPTRTI\main\employer_toolkit')
with cd('\Work\BPTRTI\main\employer_toolkit'):
result = local('ant viewEmployee_git')
if result.failed and not confirm("Tests failed. Continue anyway?"):
abort("Aborting at user request.")
def deploy():
process = "View Employee"
os.chdir('\Documents and Settings\markw\GitTest')
with cd('\Documents and Settings\markw\GitTest'):
local('git add images')
local('git commit -m "Latest Selenium screenshots for %s"' % (process))
local('git push -u origin master')
def viewEmployee():
#test()
deploy()
It Works \o/ Hurrah.
You should look into Fabric. http://docs.fabfile.org/en/1.4.1/index.html. Automated server deployment tool. I have been using this quite some time, it works pretty fine.
Here is my one of the application which uses it, https://github.com/kracekumar/sachintweets/blob/master/fabfile.py
It looks like you can do this:
index = repo.index
index.add(['images'])
new_commit = index.commit("my commit message")
and then, assuming you have origin as the default remote:
origin = repo.remotes.origin
origin.push()
I've looked all around Google and its archives. There are several good articles, but none seem to help me out. So I thought I'd come here for a more specific answer.
The Objective: I want to run this code on a website to get all the picture files at once. It'll save a lot of pointing and clicking.
I've got Python 2.3.5 on a Windows 7 x64 machine. It's installed in C:\Python23.
How do I get this script to "go", so to speak?
=====================================
WOW. 35k views. Seeing as how this is top result on Google, here's a useful link I found over the years:
http://learnpythonthehardway.org/book/ex1.html
For setup, see exercise 0.
=====================================
FYI: I've got zero experience with Python. Any advice would be appreciated.
As requested, here's the code I'm using:
"""
dumpimages.py
Downloads all the images on the supplied URL, and saves them to the
specified output file ("/test/" by default)
Usage:
python dumpimages.py http://example.com/ [output]
"""
from BeautifulSoup import BeautifulSoup as bs
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
def main(url, out_folder="C:\asdf\"):
"""Downloads all the images at 'url' to /test/"""
soup = bs(urlopen(url))
parsed = list(urlparse.urlparse(url))
for image in soup.findAll("img"):
print "Image: %(src)s" % image
filename = image["src"].split("/")[-1]
parsed[2] = image["src"]
outpath = os.path.join(out_folder, filename)
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlparse.urlunparse(parsed), outpath)
def _usage():
print "usage: python dumpimages.py http://example.com [outpath]"
if __name__ == "__main__":
url = sys.argv[-1]
out_folder = "/test/"
if not url.lower().startswith("http"):
out_folder = sys.argv[-1]
url = sys.argv[-2]
if not url.lower().startswith("http"):
_usage()
sys.exit(-1)
main(url, out_folder)
On windows platform, you have 2 choices:
In a command line terminal, type
c:\python23\python xxxx.py
Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.
For your posted code, the error is at this line:
def main(url, out_folder="C:\asdf\"):
It should be:
def main(url, out_folder="C:\\asdf\\"):
Usually you can double click the .py file in Windows explorer to run it. If this doesn't work, you can create a batch file in the same directory with the following contents:
C:\python23\python YOURSCRIPTNAME.py
Then double click that batch file. Or, you can simply run that line in the command prompt while your working directory is the location of your script.
Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
Your command should include the url parameter as stated in the script usage comments.
The main function has 2 parameters, url and out (which is set to a default value)
C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
If you want to run .py files in Windows, Try installing Git bash
Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads"
File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split
ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!
How do i get a basic web2py server up and running on
PythonAnywhere?
[update - 29/05] We now have a big button on the web tab that will do all this stuff for you. Just click where it says Web2Py, fill in your admin password, and you're good to go.
Here's the old stuff for historical interest...
I'm a PythonAnywhere developer. We're not massive web2py experts (yet?) but I've managed to get web2py up and running like this:
First download and unpack web2py:
wget http://www.web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
Go to the PythonAnywhere "Web" panel and edit your wsgi.py. Add these lines:
import os
import sys
path = '/home/my_username/web2py'
if path not in sys.path:
sys.path.append(path)
from wsgihandler import application
replacing my_username with your username.
You will also need to comment out the last two lines in wsgi.py, where we have the default hello world web.py application...
# comment out these two lines if you want to use another framework
#app = web.application(urls, globals())
#application = app.wsgifunc()
Thanks to Juan Martinez for his instructions on this part, which you can view here:
http://web2py.pythonanywhere.com/
then open a Bash console, and cd into the main web2py folder, then run
python web2py.py --port=80
enter admin password
press ctrl-c
(this will generate the parameters_80.py config file)
then go to your Web panel on PythonAnywhere, click reload web app,
and things should work!
You can also simply run this bash script:
http://pastebin.com/zcA5A89k
admin will be disabled because of no HTTPS unless you bypass it as in the previous post. It will create a security vulnerability.
Pastebin was down, I retrieved this from the cache.
cd ~
wget -O web2py_srz.zip http://web2py.com/examples/static/web2py_src.zip
unzip web2py_src.zip
echo "
PATH = '/home/"`whoami`"/web2py'
import os
import sys
sys.stdout = sys.stderr
os.chdir(PATH)
if not './' in sys.path[:1]: sys.path.insert(0,'./')
from gluon.main import wsgibase as application
" > /var/www/wsgi.py
cd web2py
python -c "from gluon.main import save_password; save_password(raw_input('admin password: '),433)"
I have recently summarized my experience with deployment of Web2Py on PythonAnywhere here
Hope it helps
NeoToren
I'll try to add something new to the discussion. The EASIEST way I've found is to go here when you aren't logged in. This makes it so you don't have to mess around with the terminal:
https://www.pythonanywhere.com/try-web2py
Come up with a domain name, then you'll get redirected to a page showing your login information and created dashboard for that domain. From there just create an account so your app isn't erased after 24 hours. When you sign up, your app has a 3 month expiry date (if you're not paying). I believe this is a new policy. Then simply go to https://appname.pythonanywhere.com/admin and then enter the password you were given and then upload your Web2Py file into the dashboard and then visit the page.
I'm not sure how to upload a Web2Py app on PythonAnywhere for an existing account, but that's the easiest method I've found.