Python Load Serialization Files

1

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

My question is good practice in loading files.

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. This makes changes to the file with the instances and another program reads and executes the created codes. Just like an HTML editor.

I've seen the serialization forms: pickle, Shelve, and Json. I did not want encrypted files.

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

Example:

file Arguments.py

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

Program that reads file Files.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 / result:

cor pt1
cor pt2

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

It works, but I would like to know if this is a good practice or if there is any other way to do this "instance import" without encrypting the text.

    
asked by anonymous 06.01.2017 / 14:56

1 answer

1

Well, as I said, running an external script in the way you suggest is dangerous because you have no way of knowing what's going on there.

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 configuration file

{
    "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 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)
--------------------
    
06.01.2017 / 16:17