2

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?

2
  • What version of Python are you using? Commented Mar 27, 2015 at 20:04
  • 3
    there's pipes.quote / shlex.quote -- neither will add backslashes like you want, but both will make the string safe to pass to os.system. Commented Mar 27, 2015 at 20:08

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 think the depreciated is actually deprecated
@BhargavRao, lol yes, watching two screens simultaneously is probably not good for my grammar.
You could multithread both your eyes to work on different screens :P
@BhargavRao, think it is time to call it a night and concentrate on the large flatscreen in the corner ;)
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.