简体   繁体   中英

Python - How to see tab completion output

How can i see what tab completion returns?

Ill clarify :

Lets say im opening a bash shell, typing l and clicking TAB. Ill get all commands containing the l char.

Now, i know how to programatically enter a full command to the shell and parse the output,

for example:

def shell_output()
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    print iter(p.stdout.readline, '')

but how can i see what TAB completion shows?

Tab completion is part of readline mode. You only get readline mode if you're both in interactive mode, and on a TTY. So, when you Popen it, so its stdin is a pipe, you cannot get tab completion.

You can see this by testing without Python in the way:

$ socat TCP-LISTEN:12345 EXEC:bash &
$ nc localhost 12345
l<TAB>

Nothing happens. You may see ^I after the L , or 7 spaces, or nothing at all, but you're not going to get anything completed.

Of course you can force interactive mode, but then it'll just open /dev/tty and ignore your stdin pipe, which doesn't help.

So, what you need to do is use the pty module or the openpty or forkpty function instead of subprocess . It's not nearly as nice and high-level, but it will actually work.

Of course once you start reading bash's TTY output, you're going to start getting terminal beeps and cursor movement characters too; I hope you're prepared to deal with that.

A much better solution is to not try to send tabs at bash, just use compgen to complete things for you programmatically:

completions = subprocess.check_output('compgen -c l', shell=True).splitlines()

That -c means you only want command names. You can complete a whole slew of things—directories, filenames, env variables, etc., anything that can be completed in any context on the interactive prompt. If you want exactly the same things that are completed at the start of an empty command line, I believe that's -abc -A function (aliases, builtins, commands, and functions), but read the docs for full details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM