I have a file name that I want to pass to a program or a bash script. For example if it's my car's picture.jpg, I have to change it to my\ car\'s picture.jpg to pass it to os.system like show my\ car\'s picture.jpg. Is there a function to do it the backslashes automatically?
3 Answers
You should use the subprocess module to call shell scripts from Python. Then you don't have to worry about escaping things yourself.
import subprocess
subprocess.call(['script_name', "my car's picture.jpg"])
subprocess.call() will escape everything correctly for you. If you need to read the output of the shell script, use subprocess.check_output() instead.
Comments
You can simply pass as is and use subprocess, os.system is depreciated.
c = check_output(["file","/home/padraic/Pictures/my cars' picture.png"])
print(c)
b"/home/padraic/Pictures/my cars' picture.png: PNG image data, 1366 x 768, 8-bit/color RGB, non-interlaced\n"
To call a script use check_call, if you want to pipe you can use Popen, there are lots of example in the docs linked above including replacing-os-system.
4 Comments
I can offer several incomplete suggestions that could be helpful to you.
Use "my car's picture.jpg" -- double quotes escape single ones
Using spaces in a UNIX file system generates only headaches. You could pass the filename inside of double-quotes.
os.system('cp "my car\'s picture" myCarPicture.jpg')
If you are using filenames with backslashes in a Windows system, use raw string
r"C:\Foo\bah\baz.jpg"
pipes.quote/shlex.quote-- neither will add backslashes like you want, but both will make the string safe to pass toos.system.