Cannot Launch Interactive Program While Piping to Script in Python

こ雲淡風輕ζ 提交于 2019-12-01 11:18:57

When you pipe something to a process, the pipe is connected to that process's standard input. This means your terminal input won't be connected to the editor. Most editors also check whether their standard input is a terminal (isatty), which a pipe isn't; and if it isn't a terminal, they'll refuse to start. In the case of nano, this appears to cause it to exit with the message you included:

% echo | nano
Received SIGHUP or SIGTERM

You'll need to provide the input to your Python script in another way, such as via a file, if you want to be able to pass its standard input to a terminal-based editor.

Now you've clarified your question, that you don't want the Python process's stdin attached to the editor, you can modify your code as follows:

editorprocess = subprocess.Popen([editor or "vi", temppath],
                                 stdin=open('/dev/tty', 'r'))

The specific case of find -type f | vidir - is handled here:

foreach my $item (@ARGV) {
    if ($item eq "-") {
        push @dir, map { chomp; $_ } <STDIN>;
        close STDIN;
        open(STDIN, "/dev/tty") || die "reopen: $!\n";
    }

You can re-create this behavior in Python, as well:

#!/usr/bin/python

import os
import sys

sys.stdin.close()
o = os.open("/dev/tty", os.O_RDONLY)
os.dup2(o, 0)
os.system('vim')

Of course, it closes the standard input file descriptor, so if you intend on reading from it again after starting the editor, you should probably duplicate its file descriptor before closing it.

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