I am trying to mod AutoResume addon for KODI. Now the addon only saves current playing song an position. And after reboot it will play that song and then stop.
But I want it to begin playing the song and then play whole playlist, that was playing before.
So I tried to change the code, but I have a problem.
I am trying to read playlist id like this:
mediaFile = xbmc.Player().getPlayingFile()
position = xbmc.Player().getTime()
# The line in question:
playList = xbmc.PlayList().getPlayListId()
# Write info to file
f = open('/home/pi/autoresume.txt', 'w')
f.write(mediaFile)
f.write('\n')
f.write(repr(position))
f.write('\n')
f.write(repr(playList))
f.close()
But python gives me this:
-->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: function takes exactly 1 argument (0 given)
Traceback (most recent call last):
File "/home/pi/.kodi/addons/service.autoResume-master/default.py", line 79, in <module>
recordPosition()
File "/home/pi/.kodi/addons/service.autoResume-master/default.py", line 59, in recordPosition
playList = xbmc.PlayList().getPlayListId()
TypeError: function takes exactly 1 argument (0 given)
-->End of Python script error report<--
If I understand this correctly there is missing argument in getPlaylistId(), but this method does not need parameter:
http://mirrors.xbmc.org/docs/python-docs/stable/xbmc.html#PlayList-getPlayListId
What am I doing wrong?
XBMC has following types that have to be used if you would have some information of a Playlist:
xbmc.PLAYLIST_MUSIC
xbmc.PLAYLIST_VIDEO
So for your example you have to choose from which playlist you want this information so if you want to have the Music Playlist ID then you have to do the following:
xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getPlayListId()
Check this link for more information:
http://www.programcreek.com/python/example/77742/xbmc.PLAYLIST_VIDEO
Have you tried getPlayListId(self), if your in a class?
I had the same issue. I ended up using jsonrpc instead. The only caveat is that you can play a video file without a playlist and you have to check it with
xbmc.Player().getPlayingFile()
I think the getPlayListId is meant to take a playlist object that you already used and find its id... not necessarily find the current playing playlist. I could be wrong though.
There are 3 possible "playlists". 0 is audio, 1 is video, and not sure of 2. I poll all 3 and write into a database to preserve whatever I send to a list. These are what I use:
plid[0] = json.loads(xbmc.executeJSONRPC(
'{"jsonrpc":"2.0", "method": "Playlist.GetItems", "params":{"properties":["file"], "playlistid":0'
+ '},"id":0}'))
plid[1] = json.loads(xbmc.executeJSONRPC(
'{"jsonrpc":"2.0", "method": "Playlist.GetItems", "params":{"properties":["file"], "playlistid":1'
+ '},"id":1}'))
plid[2] = json.loads(xbmc.executeJSONRPC(
'{"jsonrpc":"2.0", "method": "Playlist.GetItems", "params":{"properties":["file"], "playlistid":2'
+ '},"id":2}'))
Edit:
I just found an easier way to see if you need getPlayingFile(). If you find the active player with jsonrpc and then check the playlist position of the playing media a position of -1 means it's not in a playlist :
data = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "method":"Player.GetActivePlayers", "id":0}'))
if xbmc.PlayList(data["result"][0]["playerid"]).getposition() < 0:
# playing file outside of play list
Related
I'm trying to use ffmpeg to get the resolution height and the audio bitrate from a video file, but I'm getting the following error that doesn't tell me much:
File "/home/user/code/python/reduce_video_size/main.py", line 94, in get_metadata
return video_streams[0]
KeyError: 0
----------------------------------------------------------------------
Ran 1 test in 0.339s
FAILED (errors=1)
so I don't know what can I do to fix it.
print(get_metadata("/home/user/code/python/reduce_video_size/test.mp4"))
def get_metadata(path):
video_streams = ffmpeg.probe(path, select_streams = "v")
if video_streams:
return video_streams[0]
If there's need for more context here is the code.
This solved it but it would still be nice to have some error checking:
def get_metadata(path):
video_stream = ffmpeg.probe(path, select_streams = "v")
return video_stream['streams'][0]
According to the source code, ffmpeg.probe returns a dictionary loaded from JSON. So, you don't need to take out the first item and the [0] can be omitted. It does obviously not have any integer indices.
I run a command in which it creates a new camera, however at the end of the said function, there is no selection nor does the function selects the object after it has run its course.
So are there any commands in which I could possible query for the last created item?
I tried using `cmds.listHistory' but that will only shows you results if there is already a selection..
Any ways in which I can get around with it?
Additionally, say I am using the following command using the
cameraShape...
aaa = "cameraShape1"
mel.eval('<Some mel-based command> cameraShape.transformX cameraShape.transformY cameraShape.transformZ;')
but when I tried writing that command in another way such as :
mel.eval('<Some mel-based command> %s.transformX %s.transformY %s.transformZ;' %aaa)
I got an error saying
# Error: not enough arguments for format string
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# TypeError: not enough arguments for format string #
Where am I writing it wrong exactly? I tried writing like %aaa, aaa, aaa still the same error occurs
Why can't you just stuff the new camera into a variable instead of relying on selection?
new_camera, new_camera_shape = cmds.camera()
You're not using the right syntax when formatting with %:
"My name is %s" % "Jon Snow" # Works for single
"My name is %s and I was born in %s" % ("Jon Snow", "Winterfell") # Multiple
Personally I prefer format() as it's suppose to be more forward compatible for Python 3:
"My name is {0} and I was born in {1}".format("Jon Snow", "Winterfell")
Detect new objects:
scene_before = cmds.ls(l=True, transforms=True)
# Run command to import object here
scene_after = cmds.ls(l=True, transforms=True)
new_objs = list( set(scene_after).difference(scene_before) )
If you want to keep the last created object. You can create a class that contain a variable history where your append in your other script the last object created.
class History:
idCounter = []
def __init__(self, name):
History.idCounter.append(name)
print(History.idCounter)
for name in ['nana', 'tata', 'zaza']:
objectCreated = History(name)
I've looked through a lot of replies regarding this error, however none was helpfull for my special case and since I'm new to Python, I have difficulties applying the hints to my problem.
I have a class in a file Aheat.py that reads
class Aheat():
name = ""
time = 0
place = 0
def __init__(self,name,time,place):
self.name = name
self.time = time
self.place = place
And a file main.py where I want to read a html file, extract information, and create a list of objects of my class to work with them later on.
The (hopefully) essential part of my main.py reads
import urllib2
import re
from Aheat import Aheat
s = read something from url
ssplit = re.split('<p', s) # now every entry of ssplit contains an event
# and description and all the runners
HeatList = []
for part in ssplit:
newHeat = Aheat("foo",1,1) # of course this is just an example
HeatList.append(newHeat)
But this gives me the following error:
Traceback (most recent call last):
File "/home/username/Workspace/ECLIPSE/running/main.py", line 22, in <module>
newHeat = Aheat("foo",1,1)
TypeError: 'list' object is not callable
which is thrown when performing the second iteration.
If I take out the generation of the object of the loop, i.e.
newHeat = Aheat("foo",1,1)
for part in ssplit:
HeatList.append(newHeat)
My code executes without a problem, but this is not what I want. I'm also not sure, if I can initialize a specific number of instances a priori, since the number of objects is estimated in the loop.
I'm using Eclipse and Python 2.7.
regex is going to bite you.
<p == <pre> || <progress> || <param> || <p> || (any user created directives on a page.)
follow the links in your comments to read up on why we shouldn't parse html with regex.
Thanks, #MarkR ( btw, I was only supplementing your comment and I was agreeing with you )
Why not put the list in your class or better yet extend list functionality with your class.
class AHeat(list):
def append(self,name,time,place):
return super(AHeat,self).append([name,time,place])
# main
heatList= AHeat()
heatList.append("foo",1,2)
heatList.append("bar",3,4)
print(heatList[0])
print(heatList[1])
> ['foo', 1, 2]
> ['bar', 3, 4]
Also
I am writing a Python script to notify me when changes are made to a webpage and store the current state of the page to a file in order to resume seamlessly after rebooting.
The code is as follows:
import urllib
url="http://example.com"
filepath="/path/to/file.txt"
try:
html=open(filepath,"r").read() # Restores imported code from previous session
except:
html="" # Blanks variable on first run of the script
while True:
imported=urllib.urlopen(url)
if imported!=html:
# Alert me
html=imported
open(filepath,"w").write(html)
# Time delay before next iteration
Running the script returns:
Traceback (most recent call last):
File "April_Fools.py", line 20, in <module>
open(filepath,"w").write(html)
TypeError: expected a character buffer object
------------------
(program exited with code: 1)
Press return to continue
I've no idea what this means. I'm relatively new to Python. Any help would be much appreciated.
urllib.urlopen does not return a string, it returns a response as a file-like object. You need to read that response:
html = imported.read()
Only then is html a string you can write to a file.
As an aside, using open(filename).read() is not considered good style, because you never close the file. The same goes for writing. Try using a context manager instead:
try:
with open(filepath,"r") as htmlfile:
html = htmlfile.read()
except:
html=""
The with block will automatically close the file when you leave the block.
I have an issue, where a function returns a number. When I then try to assemble a URL that includes that number I am met with failure.
Specifically the error I get is
TypeError: cannot concatenate 'str' and 'NoneType' objects
Not sure where to go from here.
Here is the relevant piece of code:
# Get the raw ID number of the current configuration
configurationID = generate_configurationID()
# Update config name at in Cloud
updateConfigLog = open(logBase+'change_config_name_log.xml', 'w')
# Redirect stdout to file
sys.stdout = updateConfigLog
rest.rest(('put', baseURL+'configurations/'+configurationID+'?name=this_is_a_test_', user, token))
sys.stdout = sys.__stdout__
It works perfectly if I manually type the following into rest.rest()
rest.rest(('put', http://myurl.com/configurations/123456?name=this_is_a_test_, myusername, mypassword))
I have tried str(configurationID) and it spits back a number, but I no longer get the rest of the URL...
Ideas? Help?
OK... In an attempt to show my baseURL and my configurationID here is what I did.
print 'baseURL: '+baseURL
print 'configurationID: '+configurationID
and here is what I got back
it-tone:trunk USER$ ./skynet.py fresh
baseURL: https://myurl.com/
369596
Traceback (most recent call last):
File "./skynet.py", line 173, in <module>
main()
File "./skynet.py", line 30, in main
fresh()
File "./skynet.py", line 162, in fresh
updateConfiguration()
File "./skynet.py", line 78, in updateConfiguration
print 'configurationID: '+configurationID
TypeError: cannot concatenate 'str' and 'NoneType' objects
it-tone:trunk USER$
What is interesting to me is that the 369596 is the config ID, but like before it seems to clobber everything called up around it.
As kindall pointed out below, my generate_configurationID was not returning the value, but rather it was printing it.
# from generate_configurationID
def generate_configurationID():
dom = parse(logBase+'provision_template_log.xml')
name = dom.getElementsByTagName('id')
p = name[0].firstChild.nodeValue
print p
return p
Your configurationID is None. This likely means that generate_configurationID() is not returning a value. There is no way in Python for a variable name to "lose" its value. The only way, in the code you posted, for configurationID to be None is for generate_configurationID() to return None which is what will happen if you don't explicitly return any value.
"But it prints the configurationID right on the screen!" you may object. Sure, but that's probably in generate_configurationID() where you are printing it to make sure it's right but forgetting to return it.
You may prove me wrong by posting generate_configurationID() in its entirety, and I will admit that your program is magic.