2017-06-07 4 views
0

! Résolu!

Dans la ligne de commande python 2 en exécutant:Impression d'octets bruts à l'aide de la variable

>>> print r"\x72" 
\x72 
python

retourne: \ x72 Mais si je fais:

>>> a = "\x72" 
>>> print a 
r 

il imprimera "r". Je sais aussi que si je fais:

>>> a = r"\x72" 
>>> print a 
\x72 

Mais ce que je veux être en mesure de le faire est de prendre:

>>> a = "\x72" 

et de le rendre ainsi je peux l'imprimer comme si elle était:

r"\x73" 

Comment puis-je convertir cela?

Édition: J'imprime des octets reçus d'un serveur.

Solution de travail:

def byte_pbyte(data): 
    # check if there are multiple bytes 
    if len(str(data)) > 1: 
     # make list all bytes given 
     msg = list(data) 
     # mark which item is being converted 
     s = 0 
     for u in msg: 
      # convert byte to ascii, then encode ascii to get byte number 
      u = str(u).encode("hex") 
      # make byte printable by canceling \x 
      u = "\\x"+u 
      # apply coverted byte to byte list 
      msg[s] = u 
      s = s + 1 
     msg = "".join(msg) 
    else: 
     msg = data 
     # convert byte to ascii, then encode ascii to get byte number 
     msg = str(msg).encode("hex") 
     # make byte printable by canceling \x 
     msg = "\\x"+msg 
    # return printable byte 
    return msg 
+2

https://stackoverflow.com/questions/7262828/python-comment-convertir-string-littéral-en-raw-string-literal – vroomfondel

+0

Donc vous voulez 'a =" \ x72 "' imprimer comme si c'était "r" \ x73 "' ? Cela n'a pas de sens car un 'print (r" \ x73 ")' entraîne l'impression de \ x73'. – martineau

+0

bien la chose principale que j'essaye de faire est d'imprimer des octets reçus d'une douille. Donc je n'ai pas le contrôle sur l'entrée. l'entrée dans mon cas va être des octets réels d'un serveur. – RoNAPC

Répondre

1

Merci à ginginsha j'ai pu faire une fonction qui convertit les octets en octets imprimables:

def byte_pbyte(data): 
    # check if there are multiple bytes 
    if len(str(data)) > 1: 
     # make list all bytes given 
     msg = list(data) 
     # mark which item is being converted 
     s = 0 
     for u in msg: 
      # convert byte to ascii, then encode ascii to get byte number 
      u = str(u).encode("hex") 
      # make byte printable by canceling \x 
      u = "\\x"+u 
      # apply coverted byte to byte list 
      msg[s] = u 
      s = s + 1 
     msg = "".join(msg) 
    else: 
     msg = data 
     # convert byte to ascii, then encode ascii to get byte number 
     msg = str(msg).encode("hex") 
     # make byte printable by canceling \x 
     msg = "\\x"+msg 
    # return printable byte 
    return msg