2014-04-19 6 views
1

Je suis novice à Python, et j'essaie d'utiliser pexpect, intéressé par le filtre d'entrée/sortie d'interagir. Mais je n'arrive pas à comprendre comment utiliser le filtre.Python pexpect module interagir méthode filtre

Sur la documentation de pexpect, en ce qui concerne la méthode Interact, il est mentionné que:

interact(escape_character=’x1d’, input_filter=None, output_filter=None) 

This gives control of the child process to the interactive user (the human at 
the keyboard). Keystrokes are sent to the child process, and the stdout and stderr 
output of the child process is printed. This simply echos the child stdout and child 
stderr to the real stdout and it echos the real stdin to the child stdin. When the 
user types the escape_character this method will stop. The default for 
escape_character is ^]. This should not be confused with ASCII 27 – the ESC 
character. ASCII 29 was 
chosen for historical merit because this is the character used by ‘telnet’ as the 
escape character. The escape_character will not be sent to the child process. 

You may pass in optional input and output filter functions. These functions should 
take a string and return a string. The output_filter will be passed all the output 
from the child process. The input_filter will be passed all the keyboard input from 
the user. The input_filter is run BEFORE the check for the escape_character. 

Mais il n'y a pas d'exemple comment utiliser l'entrée ou le filtre de sortie. La seule chose que le mentionne est, "Ces fonctions devraient prendre une chaîne et retourner une chaîne". Par exemple, si je veux ajouter "aaa" à chaque entrée utilisateur, comment puis-je le faire? (ce que le filtre doit être?)

def my_input(str): 
    return str + "aaa" 
... 
... 
c.interact(input_filter=?) 

Merci d'avance.

Répondre

1

Chaque segment d'entrée/sortie est transmis lorsque pexpect le lit dans le descripteur de fichier sous-jacent. Cela peut aller d'un octet à 1000 octets, selon ce qui se passe.

Si vous voulez ajouter quelque chose à la fin de chaque ligne, vous devez écrire une fonction qui vérifie les retours à la ligne. Quelque chose comme ça (non testé):

def filter(input): 
    return input.replace(b'\r\n', b'aaa\r\n') 

c.interact(input_filter=filter) 
+0

Merci Thomas. "filtre def (entrée):" a bien fonctionné. Je suppose que "input" est la fonction intégrée de Python. Cependant, si je veux aussi ajouter un filtre de sortie, disons "def out_filter (???)", au lieu de "input", que dois-je utiliser pour l'espace réservé "???". Il semble qu'il n'y ait pas de "sortie" de fonction intégrée. – user1748640

+0

'input' ici est juste un nom que j'ai choisi, pas la fonction intégrée Python. Il est un peu vilain de remplacer un builtin - j'étais paresseux avec mon nom variable. Appelez-le comme vous voulez, par ex. 'chunk'. –