Reputation: 751
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:
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()
Upvotes: 2
Views: 995
Reputation: 23856
I believe if you don't specify stdout
in the Popen
call it will share the same as the parent process, whose output your program is probably owning.
Try adding stdout=subprocess.DEVNULL
(or stdout=subprocess.PIPE
, in case you want to capture that output).
From the docs:
stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.
Upvotes: 1