I have made a program with which I download all my songs as mp3, however, unless I use the default name, it doesnt get saved as "song.mp3" but rather "song". Someone online suggested this :
for /R %x in (*) do ren "%x" *.mp3
But this also replaces the program's extension. converter.py now reads as converter.mp3
To make this easier and not have to rename the files all at once, I thought I would integrate this into the code by using the os module. But then the code wouldn't run the next time.
Is there a way to add a 'not' operator or something of the like so that the code replaces all extensions with '.mp3' except '.py'
What I have currently added to the program :
os.system('for /R %x in (*) do ren "%x" *.mp3')
os.system('ren converter.mp3 converter.py')
I feel like this would be easier to fix at download time rather than afterwards... but
for item in os.listdir():
if os.path.isfile(item) and not item.endswith('.py'):
os.rename(item, item + '.mp3')
Related
So I want to execute a python file which is in my program files folder using visual studio C project.(FYI using the exe file).
I know system function can execute a command. I want to say to my command that go to the python folder in appdata and then run that a python file which is in my program file folder.
I tried the following way
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37" "C:\Program Files (x86)\tool\tool.py";
system(cmd);
But it's giving me an error filename,directory name incorrect. Also it's an application so it should be user specific. how to i replace %user% with the actual username.
The second approach I tried is to set the python as environment variable. and then run
char cmd[] = "python " "C:\Program Files (x86)\tool\tool.py";
Since there is a space between program and files. the error says cannot find C:\Program. how do i say the compiler to include space as a part of the directory?
Let's talk.
First I don't think that
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37" "C:\Program Files (x86)\tool\tool.py";
does what you think it does. When you put two strings like that together the compiler treats it as one long string and you will not get a space between the "...Python37" and "C:...". Better to just make that one string and put your space delimiter in.
For example:
char cmd[] = "C:\Users\%user%\AppData\Local\Programs\Python\Python37 C:\Program Files (x86)\tool\tool.py";
The next issue is that C strings reserve the '\' (back-slash) character as an "escape" character. There's a history lesson in that terminology but that's for another day. The important part is that it allows you to put characters into strings that you would not normally be able to. Examples are things like tabs (\t), newlines (\n), etc. Whenever the compilers sees a "\" it will be expecting another character to complete the "escape sequence". If you actually want a backslash you have to put in two.
For example:
char cmd[] = "C:\\Users\\%user%\\AppData\\Local\\Programs\\Python\\Python37 C:\\Program Files (x86)\\tool\\tool.py";
Next, you are using an environment variable expansion "%user%". I assume that is defined in your environment (it isn't in mine). You need to be mindful of the environment and you may want to check that things are expanding as you expect. One easy way to do this is using your same code but a different cmd string:
For example:
char cmd[] = "echo %USER% >c:\\mydir\\myoutput";
system(cmd);
It's useful to put a full path on the redirect to make sure it ends up where you expect it to. Again I'm going to assume that %USER% is correctly defined in your environment.
Next, you are referencing a file path that has a space in it. That might be why you tried to use the quotes the way you did, but in this case that doesn't help you. The system function accepts a string and for the most part doesn't much care what it is. You need something to indicate that the space is part of the file path. This is where those back-slashes can really help you.
For example:
char cmd[] = "C:\\Windows\\system32\\cmd.exe /K dir \"C:\\Program Files (x86)\"";
system(cmd);
That should open a DOS/CMD window on your desktop, execute a dir of "C:\Program Files (x86)" then leave the cmd shell open. Sometimes leaving the shell open in this way can be handy to see what the default env is.
So putting it altogether your program should look something like this:
int main() {
char cmd[] = "C:\\Users\\%user%\\AppData\\Local\\Programs\\Python\\Python37 \"C:\\Program Files (x86)\\tool\\tool.py\"";
system(cmd);
}
Hey all having a little issue with my code. I am creating a random food picker for my girlfriend whenever she tells me that she doesn't know where to eat
I am using aiys voice kit on a raspberry pi zero w and cloud text to speech API so the command process is like this
--- User Presses button
"Cloud speech is listening"
User Says "Where should we go for food"
run rndfoodpkr() ---
I also tried using omxplayer instead of mixer
def rndfoodpkr():
randomfile= random.choice(os.listdir(/home/pi/share/Programs/FoodPicker/Food/"))
file = '/home/pi/share/Programs/FoodPicker/Food' + randomfile + '/'
os.system ('mixer' + file)
rndfoodpkr() is supposed to run and select a random file inside the Food folder then mixer/omxplayer is supposed to run and play the .mp3 file however it gives this error
"sh: 1: mixer/home/pi/share/Programs/FoodPicker/Food/Wendys.mp3/: not found"
Same results for any file ie. Tacobell, McDonalds, arbys, etc
try:
file = '/home/pi/share/Programs/FoodPicker/Food' + randomfile
os.system ('mixer ' + file)
I see three problems with this code:
There is a quotation mark missing before /home on the second line. I suspect you introduced this error when posting your question, as your program would not be running at all if this error were present.
You are inserting a slash in the wrong place when you generate file -- the path you end up generating would look like
/home/pi/share/Programs/FoodPicker/FoodFilename.mp3/
^^ ^
instead of the intended
/home/pi/share/Programs/FoodPicker/Food/Filename.mp3
^ ^
A neat way of fixing this would be to assign the path to a variable instead of including it in your program twice, then use os.path.join() to combine the path components, e.g:
path = "/home/pi/share/Programs/FoodPicker/Food"
randomfile = os.path.join(path, random.choice(os.listdir(path)))
You are not including a space between the command mixer and the filename. Add one:
os.system("mixer " + randomfile)
^^^
Why are you suffixing the file name with a / character? That's possibly telling whatever application you're passing it to that it's a directory (so it could, for example, play every file in that directory - no necessarily the case but it certainly wouldn't be totally bizarre behavior).
See for example, the following transcript:
>> touch wendy.mp3
>> aplay wendy.mp3/ # Note the / at the end.
wendy.mp3/: Not a directory
In any case, I suspect the problem may be the missing / between the path and the file name, and the missing space between the command and the argument. That's likely to give you a full command of:
mixer/home/pi/share/Programs/FoodPicker/FoodWendys.mp4
So the first think I would try would be to move the / to where it belongs and put the space in, something like:
cmd = 'mixer /home/pi/share/Programs/FoodPicker/Food/{}'.format(randomfile)
cmd = 'mixer {}'.format(os.path.join('/home/pi/share/Programs/FoodPicker', randomfile))
The latter (with os.path.join) is considered more portable.
If your code still doesn't work after making those changes (or you want to debug), just print out the command before using it:
print("Command is '{}'".format(cmd))
A great many problems can be solved just by looking at what the computer is seeing(1).
(1) This also works for wives, apparently :-)
I found a solution myself that works great
def rndfoodpkr ():
path = "/home/pi/share/Programs/FoodPicker/Food"
randomfile = os.path.join(path, random.choice(os.listdir(path)))
mixer.init()
mixer.music.load(randomfile)
mixer.music.play()
Thank you guys for the help!
I wrote this code and it is failing at line 11 on the "target_dir" command with invalid syntax I have a vm ubuntu and I just copy and pasted the code and it worked there but not in my win7 and I am not sure why. I was reading another question with similar code but it had a different error and noticed that someone said that some of these commands where obsolete so I was just wondering if that is so and I would just drop this book and move on to another one i just got.
Thanks in advance for the help,
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"D:\\Warlock"', 'C:\\Druid'
# Notice we had to use double quotes inside the string for names with spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = r'C:\Backup' # Remember to change this to what you will be using
# 3. The files are backed up into zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip commnad to put the files in a zip archive
zip_commnad = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
print(zip_command)
#Run the backup
if os.system(zip_command) == 0:
print('Successful backup', target)
else:
print('Backup FAILED')
source = ['"D:\\Warlock"', 'C:\\Druid' is missing an end bracket. Should be source = ['"D:\\Warlock"', 'C:\\Druid'].
Edit: Also,
zip_commnad = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
print(zip_command)
should be
zip_command = "7z a -tzip {0} {1}" .format(target, ' '.join(source))
print(zip_command)
i.e., spell command correctly and fix the indentation. Additionally, although defining the backup paths like you are is not an error, I'd agree with abaumg's comment that using raw strings would be a lot clearer.
In Python, an invalid syntax error often means that there is a syntax error, one or more lines above the line number that is reported.
Use an editor that does parenthesis hightlighting so that you can move your cursor along the line and see where there are missing or too many parentheses, braces, brackets, etc.
Also, you might want to have a look at the os.path module and get rid of the C: and the \ from your filenames. It is possible to make Python code portable between Linux and Windows. The drivenames could come from options (sys.argv) or a config file (ConfigParser) and the \ can be replaced by a single / and then you can use os.path.normcase() to normalize it for the current OS.
In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
You need a file editor, not python.
Install the appropriate VIM variant for your operating system
Open the file you want to modify using VIM
Type: :%s/^/,/
Type: :wq
If you are in UNIX environment, open up a terminal, cd to the directory your file is in and use the sed command. I think this may work:
sed "s/\n/\n,/" your_filename.py > new_filename.py
What this says is to replace all \n (newline character) to \n, (newline character + comma character) in your_filename.py and to output the result into new_filename.py.
UPDATE: This is much better:
sed "s/^/,/" your_filename.py > new_filename.py
This is very similar to the previous example, however we use the regular expression token ^ which matches the beginning of each line (and $ is the symbol for end).
There are chances this doesn't work or that it doesn't even apply to you because you didn't really provide that much information in your question (and I would have just commented on it, but I can't because I don't have enough reputation or something). Good luck.
Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? You can't go back and edit what those previous commands did (as they have been executed), but you can hit the up arrow to flip through those commands to edit and reexecute them.
If you're doing anything very long, the best bet is to write your program into your text editor of choice, save that file, then launch it.
Adding a comma to the start of every line with Python:
import sys
src = open(sys.argv[1])
dest = open('withcommas-' + sys.argv[1],'w')
for line in src:
dest.write(',' + line)
src.close()
dest.close()
Call like so: C:\Scripts>python commaz.py cc.py. This is a bizzare thing to do, but who am I to argue.
Code is data. You could do this like you would with any other text file. Open the file, read the line, stick a comma on the front of it, then write it back to file.
Also, most modern IDEs/text editors have the ability to define macros. You could post a question asking for specific help for your editor. For example, in Emacs I would use C-x ( to start defining a macro, then ',' to write a comma, then C-b C-n to go back a character and down a line, then C-x ) to end my macro. I could then run this macro with C-x e, pressing e to execute it an additional time.
I have been going through "A byte of Python" to learn the syntax and methods etc...
I have just started with a simple backup script (straight from the book):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
Right, it fails. If I run the zip command in the terminal it works fine. I think it fails because the zip_command is never actually run. And I don't know how to run it.
Simply typing out zip_command does not work. (I am using python 3.1)
Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? It could be that zip isn't on the path when Python launches the command.
It would help us if you could format your code as code; select the code parts, and click on the "Code Sample" button in the editor toolbar. The icon looks like "101/010" and if you hold the mouse pointer over it, the yellow "tool tip" box says "Code Sample <pre></pre> Ctrl+K"
I just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. So the bold lines are comments. So far so good.
Your strings seem to contain backslash characters. You will need to double each backslash, like so:
target_dir = 'E:\\Backup'
This is because Python treats the backslash specially. It introduces a "backslash escape", which lets you put a quote inside a quoted string:
single_quote = '\''
You could also use a Python "raw string", which has much simpler rules for a backslash. A raw string is introduced by r" or r' and terminated by " or ' respectively. examples:
# both of these are legal
target_dir = r"E:\Backup"
target_dir = r'E:\Backup'
The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct.
Another thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. Especially PATH.
Here is a suggested example:
set
echo Trying to run zip...
zip
Put those in a batch file called C:\mytest.cmd, and then have your Python code run it:
result_code = os.system("C:\\mytest.cmd")
print('Result of running mytest was code', result_code)
If it works, you will see the environment variables printed out, then it will echo "Trying to run zip...", then if zip runs it will print a message with the version number of zip and how to run it.
zip command only work in linux not for windows.. thats why it make an error..