So my path:

/Users/work/Desktop/My Folder/My File.txt

My Folder and My File have spaces. Of course, in Terminal, when you tab for autocompletion it would do /Users/work/Desktop/My\ Folder/My\ File.txt.

My problem is when I use that path in python as such:

from subprocess import Popen

def print_rc(file):
    with open(file, 'r') as infile:
        p = Popen(["lpr -o page-ranges=1-2"], stdin=infile)
        output = p.communicate()[0]

I get an error that no such file or directory error. When I do os.path.exists('/Users/work/Desktop/My Folder/My File.txt'), it turns out as True. So I think the problem has to do with the spaces.

What would I need to do to make convert the python string into something bash can understand then?

  • No, that's not why. – Ignacio Vazquez-Abrams May 4 '18 at 6:39
  • How come I call 'lpr' with that same file directly from the command line but not from Python? My printer prints when on the command line. – dearprudence May 4 '18 at 7:21
  • WAIT! shell=True needs to be added to the constructor of Popen. lol – dearprudence May 4 '18 at 7:24
  • Because you're doing it correctly on the command line. – Ignacio Vazquez-Abrams May 4 '18 at 7:24

subprocess.Popen doesn't want a shell command line. It wants an array of exec arguments:

Popen(["lpr", "-o", "page-ranges=1-2"])
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.