In my understanding, subprocess.Popen() should create a new process and does not block the main one.
However, the following scripts do not print until they have finished.
It appears that the print job is added after the button is pressed, but for some reason not directly executed. (At least Ubuntu shows an added print job.)
Why does this behavior occur?
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
lpr = subprocess.Popen("/usr/bin/lpr", # on raspbian: /usr/bin/lp
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, # proposed by user elias
close_fds=True) # proposed by user elias
output = "Username: testuser\n".encode() \
+ "Password: p4ssw0rd\n".encode()
lpr.stdin.write(output)
while True:
pass
The above script does not print anything, even after it has been quit using ctrl-c. (The print job seems to stay in the queue.)
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import time
lpr = subprocess.Popen("/usr/bin/lpr", # on raspbian: /usr/bin/lp
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, # proposed by user elias
close_fds=True) # proposed by user elias
output = "Username: testuser\n".encode() \
+ "Password: p4ssw0rd\n".encode()
lpr.stdin.write(output)
time.sleep(20)
This prints after 20 seconds (when the script ends).
About the execution environment:
- os: ubuntu 18.04 (does also occur on raspbian)
- python: 3.6.5
- printer: a network printer via CUPS (does also occur when connected via USB)
SOLUTION:
As can be seen in the comments of the answer from user elias, the behavior was caused by buffering.
The problem was solved by closing stdin.
lpr.stdin.close()