Using lpr to print a file whose path has spaces

0

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?

dearprudence

Posted 2018-05-04T06:38:14.303

Reputation: 1

No, that's not why. – Ignacio Vazquez-Abrams – 2018-05-04T06:39:24.643

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 – 2018-05-04T07:21:21.000

WAIT! shell=True needs to be added to the constructor of Popen. lol – dearprudence – 2018-05-04T07:24:22.940

Because you're doing it correctly on the command line. – Ignacio Vazquez-Abrams – 2018-05-04T07:24:28.057

Answers

2

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

Popen(["lpr", "-o", "page-ranges=1-2"])

user1686

Posted 2018-05-04T06:38:14.303

Reputation: 283 655