Detect Window's Default Media Player - python

I'm trying to detect Window's default media player path so that I can access it from my Python/wxPython program. My specific need is to make a list of all media files and play it using the player.

Based on the comments above, it looks like you decided to go in another direction with this. Your question made me curious though so I did some hunting around anyway.
File associations are stored in the Windows Registry. The way to access Windows Registry information via python is to use the _winreg module (available in versions 2.0 and later). Individual file association information for the current user will be stored at subkeys named as follows:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.wmv\UserChoices
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.mpeg\UserChoices
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.avi\UserChoices
etc, etc for any specific file format you are looking for.
Here is a small example script I've written to access this information and store it as a list:
import _winreg as wr
# Just picked three formats - feel free to substitute or extend as needed
videoFormats = ('.wmv', '.avi', '.mpeg')
#Results written to this list
userOpenPref = []
for i in videoFormats:
subkey = ("Software\\Microsoft\\Windows\\CurrentVersion" +
"\\Explorer\\FileExts\\" + i + "\\UserChoice")
explorer = wr.OpenKey(wr.HKEY_CURRENT_USER, subkey)
try:
i = 0
while 1:
# _winreg.EnumValue() returns a tuple:
# (subkey_name, subkey_value, subkey_type)
# For this key, these tuples would look like this:
# ('ProgID', '<default-program>.AssocFile.<file-type>', 1).
# We are interested only in the value at index 1 here
userOpenPref.append(wr.EnumValue(explorer, i)[1])
i += 1
except WindowsError:
print
explorer.Close()
print userOpenPref
Output:
[u'WMP11.AssocFile.WMV', u'WMP11.AssocFile.avi', u'WMP11.AssocFile.MPEG']
with WMP11 = Windows Media Player 11
Hope this was helpful.
Sources:
python docs, effbot tutorial

Related

How to know a material name of a PID in ABAQUS odb file(not MDB file) using Python scripting?

Here I need to know how to find the name of the material for each PID. I'm a beginner so every answer can help me a lot.
odb= odbAccess.openOdb(path=(path+file), readOnly=True)
tag="ERT"
step = []
step.append(odb.steps[odb.steps.keys()[0]])
frame = []
frame.append(step[0].frames[-1])
assembly = []
assembly.append(odb.rootAssembly)
instance = []
instance.append(assembly[0].instances[instance_n])
PIDs = []
for key in instance[0].elementSets.keys():
if tag in key:
PIDs.append(key)
for PID in PIDs:
print(material_name[PID]) # here i need to know name of material for this PID
The information about the material or rather the section is stored within the section object. If you know your sections (you did not mention if you have actual access to the model). If not then you also have to obtain the materials information and the section information from the odb.
What you CAN do within your set is this
odb = odbAccess.openOdb(path=(path+file), readOnly=True)
my_elset = odb.rootAssembly.instances[0].elementSets[setname]
element_from_set = my_elset.elements[0] # list with mesh element object, e.g. first
sec_category = element_from_set[0].sectionCatergory
section category contains several informations about the underlying section. In case you do know your sections and the corresponding material (maybe stored in a file after creating the model): good.
Id not, you have to further obtain section information e.g. by:
odb.sections[sectionname]
which amongst other contains the material for each section in the odb.
In any case you I think you would make your live easier if you obtained that information directly within the mdb if possible.
The above examples are only rudimentary, you might need to loop over them in case you don't have explicit setnames but they can also be obtained.
EDIT:
As a general recommendation: You can try all of this in the command line either by opening abaqus command promt and typing
abaqus python
and you get abaqus python shell or, with open abaqus you can use the shell at the bottom (>>> on yellow ground) or the PDE.

Tempfile path returning int python3

I would like to know if there is a way to find the path of a temporary file without it returning an int (15 in my case). I would like to return a string (or an object in which I can then turn into one, please detail how) path is the path to the temp file (and the name of it). Example: /Users/FooBar/Python3.6/Modules/TempFile/Opus/THE_TEMP_FILE or something like that. I have already written a small .wav file to it and would like to get the path to get the playing time/duration of it using os .stat(). I want to use a temporary file because I am lazy and I do not want to do a lot of 'special' code for the four different operating systems I am trying to this program on. Here is my code:
import pygame, time, os, tempfile
import urllib.request as ur
pygame.init() # Initialize the pygame
DISPLAYSURF = pygame.display.set_mode((1, 1)) # Sets display. Needed to play sound
sound = input('What sound should play: ') # Asks which sound
url = 'http://207.224.195.43:8000/' + sound # Gets server url
response = ur.urlopen(url) # Open url
data = response.read() # Create byte like object containing .wav code
f = tempfile.TemporaryFile() # Create TempFile
f.write(data) # Write .wav data gotten from server
f.seek(0) # Prepare to read it
soundObj = pygame.mixer.Sound(f.read()) # Load sound to be played
f.seek(0) # Prepare to read it
statbuf = os.stat(f.name) # Gets stats from TempFile. Returns int, I want to fix that
mbytes = statbuf.st_size / 1024 # Gets 'not real' sound duration
soundObj.play() # Plays sounds
time.sleep(mbytes / 200) # Gets 'real' sound duration and waits
soundObj.stop() # Stops sounds once done
Let me know (comment) if you have any suggestions. I have looked at a few sites, one of which was on stack-overflow, one that you could mistake to be a duplicate of this question. It was about Django which as I understand is entirely different then python. Thanks for possibly answering this question. Remember, I am not looking for a confirmation on this is an issue, I already know that. Please give me a possible answer to the question as soon as you can.
Thanks!
-User 9311010
The whole point of tempfile.TemporaryFile is that there is no name for the file, if at all possible:
… Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.
If you want a temporary file with an accessible filename, use NamedTemporaryFile:
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system… That name can be retrieved from the name attribute of the returned file-like object.
However, I don't think you need a filename in the first place. Do you only want one so you have something to pass to stat? In Python 3.3+, you can pass a file object (like f) to stat instead of its name. In older versions, you can use fstat with the file's descriptor (fileno()).

For loop with Python for ArcGIS using Add Field and Field Calculator

I'll try to give a brief background here. I recently received a large amount of data that was all digitized from paper maps. Each map was saved as an individual file that contains a number of records (polygons mostly). My goal is to merge all of these files into one shapefile or geodatabase, which is an easy enough task. However, other than spatial information, the records in the file do not have any distinguishing information so I would like to add a field and populate it with the original file name to track its provenance. For example, in the file "505_dmg.shp" I would like each record to have a "505_dmg" id in a column in the attribute table labeled "map_name". I am trying to automate this using Python and feel like I am very close. Here is the code I'm using:
# Import system module
import arcpy
from arcpy import env
from arcpy.sa import *
# Set overwrite on/off
arcpy.env.overwriteOutput = "TRUE"
# Define workspace
mywspace = "K:/Research/DATA/ADS_data/Historic/R2_ADS_Historical_Maps/Digitized Data/Arapahoe/test"
print mywspace
# Set the workspace for the ListFeatureClass function
arcpy.env.workspace = mywspace
try:
for shp in arcpy.ListFeatureClasses("","POLYGON",""):
print shp
map_name = shp[0:-4]
print map_name
arcpy.AddField_management(shp, "map_name", "TEXT","","","20")
arcpy.CalculateField_management(shp, "map_name","map_name", "PYTHON")
except:
print "Fubar, It's not working"
print arcpy.GetMessages()
else:
print "You're a genius Aaron"
The output I receive from running this script:
>>>
K:/Research/DATA/ADS_data/Historic/R2_ADS_Historical_Maps/Digitized Data/Arapahoe/test
505_dmg.shp
505_dmg
506_dmg.shp
506_dmg
You're a genius Aaron
Appears successful, right? Well, it has been...almost: a field was added and populated for both files, and it is perfect for 505_dmg.shp file. Problem is, 506_dmg.shp has also been labeled "505_dmg" in the "map_name" column. Though the loop appears to be working partially, the map_name variable does not seem to be updating. Any thoughts or suggestions much appreciated.
Thanks,
Aaron
I received a solution from the ESRI discussion board:
https://geonet.esri.com/thread/114520
Basically, a small edit in the Calculate field function did the trick. Here is the new code that worked:
arcpy.CalculateField_management(shp, "map_name","\"" + map_name + "\"", "PYTHON")

Python (2.7): Simple version checker

A preface: I'm a beginner at Python. I've tried guides for learning but I am awful at learning like that, so I'm trying to make a super simple update checker to get started that I slowly build upon. I've grabbed some code I found on here and modified it a bit, and alas, it doesn't work. It reads the local and external .txt files and prints their output (just to check that it's reading them correctly). It then fails at the if/elif/elif/else statement thing in some way, so some help there would be great!
It's currently telling me "NameError: global name 'i' is not defined" however I've gone through several different errors at this point and am really just looking for a solution, and from there I can work backwards. Thanks!
import Tkinter
import urllib
import time
print "test"
#previously self within the brackets
def updateCheck():
update = False
updateWindow = Tkinter.Toplevel()
updateWindow.title(string="Update Checker")
updateWindow.resizable(False, False)
#gets local version (file currently says "1.0")
localSource = open('version.txt', 'r')
localContents = localSource.read()
print "local version = " + localContents
#gets server version (file currently says "1.1")
serverSource = urllib.urlopen("http://raw.github.com/SamHH/ccr-version/master/version.txt")
serverContents = serverSource.read()
print "server version = " + serverContents
#checks for updates by comparing the above two -- doesn't work
if serverContents[i] > localContents[i]:
dataLabel = Tkinter.Label(updateWindow,text="\n\nThere is an update available.\n\n")
dataLabel.pack()
#need a way of opening a .url file in the same folder here, if possible
elif serverContents[i] < localContents[i]:
dataLabel = Tkinter.Label(updateWindow,text="\n\nYour installation appears to be broken.\n\n")
dataLabel.pack()
#need a way of opening a .url file in the same folder here, if possible, again
elif serverContents[i] == localContents[i]:
versionLabel = Tkinter.Label(updateWindow,text="\n\nYou are already running the most up to date version.\n\n")
versionLabel.pack()
#need a way of opening a .exe file in the same folder this time, if possible
else:
versionLabel = Tkinter.Label(updateWindow,text="\n\nYour install is corrupted. Doh!\n\n")
versionLabel.pack()
updateCheck()
if serverContents[i] > localContents[i]:
Notice that you never initialized i to a default value. It is looking up in your code to see if you had defined and set it outside the function (which you did not).
Put in a loop
for i in range(len(serverContents)):
You should also check that both lists are the same size or you will get an error when you try to index past the end.
Note that this assumes that the serverContents and localContents are both lists each of whose elements is a value to be compared. If the contents are text strings. then you will be looping over each character in the string. If that is what you want, you do not need to do it
f = '1.1a'
g = '1.1a'
f == g # shows True
f is g # shows False
This will mean that '1.1a' and '01.1a' will show different
However, this will allow for the case where version number is not totally numeric, which is a requirement if you use float(serverContents).
If both local and remove 'files' contain just a float, read one line from each and turn that into a float() so you can compare:
try:
localSource = open('version.txt', 'r')
localContents = float(localSource.readline())
except (IOError, ValueError):
versionLabel = Tkinter.Label(updateWindow,text="\n\nYour install is corrupted. Doh!\n\n")
versionLabel.pack()
return
serverSource = urllib.urlopen("http://raw.github.com/SamHH/ccr-version/master/version.txt")
serverContents = float(serverSource.readline())
You then use the localContents and serverContents names to compare:
if serverContents > localContents:
# etc.

Having a hard time with wx.Config

My problem is that I wanna make a config file for an application but things aren't as simple as they seamed. So I've seen a tutorial where a config file contained the width and the height and the values that followed the equal sign could been retrieved and used to establish the size of a frame. Been there, done that, and everything worked okey. Strangely enough this seams to work only for some key words, as if I've used in the config file, also a parameter named freq it didn't retrieved its value as it did with the width, height parameters.
for example if I have a piece of code like this:
self.cfg = wx.Config('myconf')
wid = self.cfg.ReadInt('width')
hei = self.cfg.ReadInt('height')
freq = self.cfg.ReadInt('frequency')
print wid, hei, freq
where in myconf
width=400
height=250
frequency=3000
So it displays the height, the width but not the frequency, as for freq it gives only 0, and this happens for any other word I use in the config file. I'm guessing that only certain key words can be used in the config file, so they could be recognized while using wxPython.
If so where could I get a list of those keys I could use in making a configuration file ?
Personally, I would recommend using ConfigParser which comes with Python or perhaps ConfigObj (which I like better). If you're trying to save widget attributes / settings, then you also might want to look at the PersistenManager
What you could do is reading the lines yourself:
F = open('myconf', 'r')
for line in F.read().split('\n'):
switchres = { 'frequency': print(line.split('=')[1]),
# add the rest
}
switchres[line.split('=')[0]]
wxPython is a wrapper (or binding) for wxWidgets that is a C++ library.
So wx.Config or wx.FileConfig is intended for C++ that has no specific way of treating these type of config file (still wx.Config is meant to be portable between platforms).
In Python you already have ConfigParser module, but have in mind:
that some wxPython classes work with wx.Config like wx.FileHistory,
use wx.Config if you want to use the platform specific way of storing configurations (like registry in Windows).

Categories

Resources