Python: Adding Variable paths into os.system("open"+filename) - python

I'm trying to make a script where python goes through a directory, finds all files that ends with *ref.SDAT, and then opens them all.
So far, I have the sorting of files process. The wanted files are put into reflist:
import os
import glob
import subprocess
os.chdir("/Users/BabyJ/Desktop/MRSDATA")
reflist = glob.glob('*raw_ref.SDAT')
print "These are the ref files:"
for i in reflist:
os.system('open+%s') %i
I don't know how to structure the syntax so that os.system will open all of the components of the list though.

The % operator wants the 'open+%s' string as its left-hand side. You are offering it the return value of os.system(). Also, I think you wanted a space, not a + in the string.
Try this:
os.system('open %s'%i)

I assuming judging from your use of open that you are on a Mac or Unix system. If that is the case use either of the following to get you up and running.
for i in reflist:
os.system('open ' + '%s' % i)
or:
for i in reflist:
subprocess.call('open ' + '%s' % i, shell = True)
Using subprocess is the better solution as os.system is, though not technically gone from the language, deprecated in Python per the official documentation.
Hope that helps.
EDIT:
If you're using windows sub in start for open.

Related

How to add a "not" action in cmd complex lines

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')

How to pass list of files into Python subprocess

I am trying to execute a system executable on UNIX with python. I have used op.system() to do this, but really need to use subprocess.call() instead. My op.System call is below:
os.system('gmsh default.msh_timestep%06d* animation_options.geo' %(timestep));
and works fine. It calls the program gmsh and gmsh reads a series of files specified in default.msh_timestep%06d*. I then try to do the equivalent thing with subprocess, but I get errors saying that the files are not there. Below is the subprocesses call:
call(["gmsh", "default.msh_timestep%06d*" %(timestep), "animation_options.geo"],shell=True);
Does anyone know what could be going on here? I'm admittedly a Python noob, so this might be a silly question.
Globbing is done by the shell for you. In Python, you need to do it yourself. You can use glob.glob to get file list that match the pattern:
import glob
call(["gmsh"] + glob.glob("default.msh_timestep%06d*" % (timestep,)) +
["animation_options.geo"])
If you want to use shell=True, pass a string isntead of a list of strings:
call("gmsh default.msh_timestep%06d* animation_options.geo" % (timestep,), shell=True)

JPG to PDF Nautilus script (using ImageMagick)

After searching for one without success, I decided to make my own script to convert selected JPEG files in one single PDF.
Here's the code (made with Python):
#!/usr/bin/env python
import os
n = " ".join(os.environ["NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"].splitlines())
os.system("convert " + n + " out.pdf")
The problem with this script is that it doesn't work if the files you want to convert are in a directory which name has spaces (let's say /home/myuser/My Photos/1/).
Is there any way I could fix this?
n = " ".join("'%s'" % f for f in os.environ["NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"].splitlines())
Remember to sanitize your filenames, otherwise a maliciously crafted name can make the script execute code on our machine.
Better yet, use the subprocess module instead of os.system().
subprocess.call ([ "convert" ] + os.environ["NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"].splitlines() + [ "out.pdf" ])

Learning python and having trouble with 1st program

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.

running a system command in a python script

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..

Categories