Python Load Serialization Files

Asked

Viewed 253 times

1

Hello, I’m studying Python for some time and doing some programs to join with Arduino.

My question is on good practices in file uploading.

I want to make a program that interprets files. My idea was inspired by the logic of HTML, CSS and Sonicpi. Where files are created in any editor. With this make changes to the file with the instances and another program reads and executes the created codes. Just like an HTML editor.

I’ve seen serialization forms: pickle, Shelve and Json. I didn’t want encrypted files.

But what else did what I would like is the example below with exec and Garbage Collector.

Example:

arqinstancias.py file

 pt1 = ponto('cor pt1')
 pt2 = ponto('cor pt2')

Program that reads the file Arqinstancias.py

import gc  

class ponto(object):
    def __init__(self,cor):
        self.cor = cor

exec(open("ArqInstancias.py").read())
   # execução e leitura

instancias = [i for i in gc.get_objects() if i.__class__ is ponto]
   # recebe as instancias da classe ponto

for i in range(len(instancias)):
    print(instancias[i].cor)
   # imprime o atributo cor de cada instancia.

output / output:

cor pt1
cor pt2

And if I call pt1.cor I also have output. IE, this instance has been incorporated into the program.

It works, but I wonder if this is a good practice or if there is some other way to do this "import instances" without encrypting the text.

  • I’m not sure I understand your need, but just from hitting my eye, it seems to me that your approach to running an external script is potentially unsafe. Someone with bad intentions can create anything you will run without knowing... If you want to receive data points, isn’t it easier (and safe) to simply read a yaml, xml or json file, for example? All these are open text data, and are not encrypted.

  • Hello Thank you. I understand the risk of this approach. My question is if I care about xml, json if I will have the instances available in memory.

  • My goal is a program that reads a file, interprets the data and printa on the screen. Ex: pt1(x,y). pt2(w,z) and when I open it in the program it with Tkinter shows the points in the positions (x,y) and (w,z)

  • See more json and xml examples. mto thanks!

  • Well, json and xml are not encrypted but have an organization of their own. E creating/editing code in the format is complicated. I search a way to embed the instances created as if I had manually typed. I don’t know if it’s feasible.

  • Okay. Well, I offered an answer that might help you. Take a look.

Show 1 more comment

1 answer

1


Well, like I said, running an external script the way you suggest is dangerous because you have no way of knowing what’s there to run.

If your need is only to receive data that is easily configurable (by the user) in text format, how about using JSON for example? Here’s a suggestion:

JSON file of configuration

{
    "pontos" : [
        {
            "nome": "pt1",
            "cor": "black",
            "x": 10,
            "y": 20
        },
        {
            "nome": "pt2",
            "cor": "blue",
            "x": 43,
            "y": 68
        }
    ]
}

Code that reads this file

import sys
import json

# ===================================
def main(args):
    """
    Entrada principal do programa.

    Parâmetros
    ----------
    args: lista
        Lista de argumentos recebidos na linha de comando. Não é utilizado.

    Retornos
    --------
    exitCode: int
        Código de saída do programa (que pode ser utilizado como errorlevel em
        chamadas no sistema operacional).
    """

    with open('ArqInstancias.json') as file:
        data = json.load(file)

        pontos = data['pontos']
        for ponto in pontos:
            print('-' * 20)
            print('Nome do ponto: {}'.format(ponto['nome']))
            print('Cor do ponto: {}'.format(ponto['cor']))
            print('Coordenadas do ponto: ({:02d}, {:02d})'.format(ponto['x'], ponto['y']))
            print('-' * 20)

    return 0

# ===================================
if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Exit from this program

--------------------
Nome do ponto: pt1
Cor do ponto: black
Coordenadas do ponto: (10, 20)
--------------------
--------------------
Nome do ponto: pt2
Cor do ponto: blue
Coordenadas do ponto: (43, 68)
--------------------
  • Hunmnmn... man, thank you, it’s not so simple to create but I think it’s the best way to do it. Seeing ident in this way really isn’t that complex. Thank you very much!

  • Why isn’t it so simple to create? What is the difficulty in creating? I don’t understand.

  • I saw some examples without identação... Sonipi must use similar things. However, it is a program beeem more complex and omits keys and markups. but it must have its own interpreter for such.

  • Indentation in JSON, you say? It is not a problem as long as it is in the correct format. The indentation is just to make it easier to read for a human, but you can take out all the newline and spaces and it will work the same way. I don’t understand what "omit keys and markings" is, and I don’t know what Sonipi is, but you didn’t mention him. If you need to do an integration with this Sonipi guy, well, then maybe you need to do it in its format. But nothing stops you from building a converter and keeping your setup as easy as it is for you on a day-to-day basis.

  • If your "weirdness" (for lack of a better word) is with the syntax of the JSON file, well, maybe you get along better with the YAML. Its formatting is much simpler (even, it can be argued, more humanly readable) and has a package called Pyyaml for your reading in Python: http://stackoverflow.com/questions/6866600/yaml-parsing-and-python

  • Another thing: if the answer helped you, please consider accepting it.

  • Sonipi was only inspiration anyway. In it you can make live coding of music. Write in the program’s own editor and the program will interpret, continuously. My intention is to make a live coding with led lights. Not only live but also create scenarios and "animations". In this I will create loops, lines, geometric figures, add effects and etc.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.