Im having some problems playing a random sound using mpg321.
First I make a list of all the sounds and also store the length in a variable I then create a random number between 0 and the length of that list. My problem is I do not know how to add that to the string inside os.system() for the file path.
sounds = os.listdir('./sounds/') # creates list of all sound names
totalSounds = len(sounds)
sound_number = random.randint(0, len(sounds))
next_sound = str(sounds[sound_number])
soundPlaying = True
os.system('mpg321 ./sounds/%s') % next_sound
soundPlaying = False
I have tried using %s and putting the variable in after ./sounds/ but I get a syntax error saying os.system() only takes one argument.
Any help is appreciated.
The problem is that you need to do string formatting on the string, not on the function call
os.system('mpg321 ./sounds/%s'%next_sound)
By the way, I would use subprocess, which provides a much more handsome API than os.system! (https://docs.python.org/3/library/subprocess.html#subprocess.call)
import subprocess
subprocess.call(["mpg321", "./sounds/%s" % next_sound])
Related
beginer question:
I often have to repeat the same line of code 10 times for 10 different variables (i read you can't or should not create variable dynamically)
I thought to help me once i written it once I could iterate with a find replace (I am currently doing it in word)
I wrote this but get tons of error when i input code like if console trying to execute the code. what am i missing? is it because i paste it i the console does it need to be imported from a ext file ?
LineOfCode = input("Enter the code you want to iterate the iteration variable need be 8")
for i in range(10):
LineOfCode.replace("8",str(i))
print(LineOfCode)
Your code is almost correct:
String.replace() returns a new string with the changes, doesn't change the existing string. So the code should be like:
LineOfCode = input("Enter the code you want to iterate the iteration variable need be 8")
for i in range(10):
var = LineOfCode.replace("8", str(i))
print(var)
The question isn't clear enough, so if this isn't what you wanted, edit the question.
Besides this, you can use Visual Code as an IDE, it'll make things much, much easier than Word.
About the errors, I think you might be trying to run the code directly in console. Instead of typing only the file name, type python file.py, assuming the file name is file. The file must be a python file (ending with .py), also it shouldn't be saved as a word file. It must be plain text.
If you want to run the same code on multiple variables, you can create the code as a string, and then use the builtin exec to execute it. Example:
a = 1
b = 2
c = 3
variables = ["a", "b", "c"]
for var in variables:
exec("print(" + var + ")") # print the variable before modifying
exec(var + " *= 2") # multiply the current variable by 2
exec("print(" + var + ")") # print the variable after modifying
If this is not what you need, your question was not clear enough and i misunderstood it, you just have to provide more information on what excatly you need by adding a comment under your question, in which you first type #Programmer and then your text.
I'm trying to use the "ls" python command in maya, to list certain objects with a matching string in the name in concatination with a wildcard.
Simple sample code like this:
from maya.cmds import *
list = ls('mesh*')
This code works and will return a list of objects with the matching string in the name, however, I would like to use a variable instead of hard coding in the string. More like this:
from maya.cmds import *
name = 'mesh'
list = ls('name*')
OR like this:
from maya.cmds import *
name = 'mesh'
list = ls('name' + '*')
However, in both examples, it returns an empty list unlike the first. I'm not sure why this is the case because in those examples, the string concatination should come out to 'mesh*' like the first example. I couldn't find an answer on this website, so I chose to ask a question.
Thank you.
JD
PS. If there is a better way to query for objects in maya, let me know what it's called and I'll do some research into what that is. At the moment, this is the only way I know of how to search for objects in maya.
As soon as you add quotes around your variable name like this 'name', you are actually just creating a new string instead of referring to the variable.
There are many different ways to concatenate a string in Python to achieve what you want:
Using %:
'name%s' % '*'
Using the string's format method:
'{}*'.format(name)
Simply using +:
name + '*'
All of these will yield the same output, 'mesh*', and will work with cmds.ls
Personally I stick with format, and this page demonstrates a lot of reasons why.
I am trying to make a program which takes in input song files and a format to write metatags in file. Here is a few examples of the call:
./parser '%n_-_%t.mp3' 01_-_Respect.mp3 gives me track=01; title=Respect
./parser '%b._%n.%t.mp3' The_Queen_of_Soul._01.Respect.mp3 gives me album=The_Queen_of_Sould; track=01; title=Respect
./parser '%a-%b._%n.%t.mp3' Aretha_Franklin-The_Queen_of_Soul._01.Respect.mp3 gives me artist=Aretha_Franklin; track=01; title=Respect
./parser '%a_-_%b_-_%n_-_%t.mp3' Aretha_Franklin_-_The_Queen_of_Soul_-_01_-_Respect.mp3 gives me artist=Aretha_Franklin; track=01; title=Respect
For a call on the file 01_-_Respect.mp3, I'd like to have a variable containing 01, and the other Respect.
Here %n and %t represents respectively the number and the title of the songs. The problem is that I don't know how to extract this information in bash (or eventually in python).
My biggest problem is that I don't know the format in advance!
Note: There is more information than this, for example %b for the album, %a for the artist etc.
Well, you can use the string method split to split the string by _-_.
and for taking the input from the command line, you can use sys.argv to get that.
here's an example:
import sys
number,title = sys.argv[1].split("_-_")
Update:
Surely you can pass the pattern as a first argument and the file as the second argument like that:
import sys
pattern = sys.argv[1]
number,title = sys.argv[2].split(pattern)
Now if you need more complex and dynamic processing, then Regex is your winning card!
And in order to write a good regex, you got to understand your data and your problem or you'll end up writing a glitchy regex
You can elaborate on this. It is a very simple example, though.
import re
p = re.compile('([0-1][0-1])_\-_(.*)\.mp3')
title = '01_-_Respect.mp3'
p.findall(title)
Output
[('01', 'Respect')]
I use this page to play with regex.
Update
Since the format is given, go with string slicing. Ok, pretty limited to the specific case..
number = title[:title.find('_')]
>>> number
'01'
>>> track = title[len(number) + 3:len(title)-4]
>>> track
'Respect'
Try This code:
(considering argument is given in runtime)
tmp=$1
num=echo ${tmp%%_*}
title=echo ${tmp##*_}|cut -d. -f1
Variables num and title will store the parts from the argument
I currently have the below syntax -
BEGIN PROGRAM.
import spss,spssdata
varlist = [element[0] for element in spssdata.spssdata('CARD_2_Q2_1_a').fetchall()]
varstring = " ".join(str(int(i)) for i in varlist)
spss.submit("if (Q4_2 = 2 AND CARD_2_Q2_1_a = %(varstring)s) Q4_2_FULL = %(varstring)s." %locals())
END PROGRAM.
I thought this would just loop through the values in my variable CARD_2_Q2_1_a and populate Q4_2_FULL where appropriate. It worked in long hand without Python use, but the code above doesn't change the input file at all. Any reason why this might not be working or an alternative way of doing this?
varstring will be a string of integers joined by blanks. Therefore, your test condition in the IF will never be satisfied. Hence Q4_2_FULL will never be populated. You can print out the command you are submitting to see this.
I'm not sure exactly what your desired result is, but remember that the IF command you are submitting will execute over the entire dataset.
I'm attempting to create a program which selects 10 words from a text file which contains 10+ words. For the purpose of the program when importing these 10 words from the text file, I must not import the same words twice! Currently I'm utilising a set for this however I'm greeted by a syntax error. I have some knowledge of sets and know they cannot hold the same value twice. As of now I'm clueless on how to solve this any help would be much appreciated. THANKS!
Relevent Code: (FileSelection)= open file dialog
def GameStage03_E():
global WordSet
if WrdCount >= 10:
WordSet = set()
for n in range(0,10):
FileLines = open(FileSelection).read().splitlines()
RandWrd = random.choice(FileLines)
WordSet.update(set([RandWrd]))
SelectButton.destroy()
GameStage01Button.destroy()
GameStage04_E()
elif WrdCount <= 10:
tkinter.messagebox.showinfo("ERROR", " Insufficient Amount Of Words Within Your Text File! ")
error code:
File "C:\Python34\lib\random.py", line 256, in choice
return seq[i]
`TypeError: 'set' object does not support indexing`
You can just use random.sample (2/3), so you don't have to do that yourself. You also don't need the call to list bigblind's answer suggests, because random.sample can take a set as an argument:
WordSet.update(random.sample(FileLines, 10))
That way, you can replace the entire body of that function with this:
try:
WordSet.update(random.sample(FileLines, 10))
except ValueError:
stkinter.messagebox.showinfo("ERROR", "The text file doesn't have enough words!")
I also left out that global statement, which you don't need. It's only necessary if you're assigning a new value to the variable, but all you need to do is call one of its functions, update.
This happens because random.choiceis trying to access the set as if it is a list (or some other datastructure that implements __getitem__). To solve this, change your call to random.choice to:
random.choice(list(FileLines))
This converts the set to a list before passing it to random.choice.
You can just use random.sample(the_list, 10) to get 10 distinct elements instead of repeatedly trying to add to a set using a loop.