Python script using subprocess and xclip hangs if piped in bash

老子叫甜甜 提交于 2019-12-11 01:58:56

问题


I have a python script that needs to output some values to stdin and copies another string to clipboard. I'm using the module subprocess to execute the xclip utility through Popen something like this:

# clip.py
import subprocess
from subprocess import Popen

print('PRINT_ME')
p1 = Popen(['xclip', '-selection', 'clipboard'], stdin=subprocess.PIPE)
p1.communicate(input=('PASTE_ME'.encode()))

The script works as intended: PRINT_ME is echoed in bash and PASTE_ME is available to paste, and returns imediatly.

A problem appears when the script output is piped to another command. Suppose one wants to redirect to a file and stdin using tee:

$ python clip.py|tee file.txt

The program works as supposed but not returns, i.e. shell don't give control back.

How can this could be fixed?

Some important info: the xclip utility forks itself (to cope with implementation of clipboards on X) maintaining the string avaliable to copy, when used in shell it returns immediately (it forks to background). It appears that the shell is attaching both clip.py and xclip stdin/stdout to tee.
If xclip -selection clipboard is found using ps u and killed the command returns.

I'm using Python 3.4.
Thanks


回答1:


It's not due to forking of xclip, it's due to how Python handles Popen.wait() (which is invoked with your call to communicate()) - from Python perspective xclip (silent by default) didn't close its stream so it waits... That's why everything works except for Python moving past your p1.communicate() line when piping its streams to something else (tee in this case) - it waits for all of its file handles to close...

You can either manually open and close your streams, or just configure xclip to filter STDIN to STDOUT and keep Python happy:

import subprocess

p1 = subprocess.Popen(['xclip', '-selection', 'clipboard', '-f'], stdin=subprocess.PIPE)
p1.communicate(input=('PASTE_ME'.encode()))
# etc.

Didn't test it, but it should work. If you don't want for xclip to print out to your current STDOUT just redirect it when instantiating subprocess.Popen() to None (or subprocess.DEVNULL for Python 3.x) or to any other stream handle you want.



来源:https://stackoverflow.com/questions/44553539/python-script-using-subprocess-and-xclip-hangs-if-piped-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!