How to "zoom" a file into another file in visual studio code

Asked

Viewed 34 times

-2

I am with some projects in python, and to facilitate my work, I do "sub-files", ie, I create other files and "compile" them while running the program by the function: "exec". But I came across a problem, I can’t make VSC "use" variables from "mother file". In a simpler way, it would be like splitting the same file. Would have some way, in visual studio code, to make it consider a set of files as a single file?

  • I don’t understand the question. You want to do this https://ideone.com/RJ8nNn read several files join the texts in memory and run the resulting script?

  • That’s right, !!!

1 answer

0


If you want to join the contents of multiple text files in memory use a text stream io.StringIO().

The content of io.StringIO() may be written with the inherited method io.TextIOBase.write() or with the built-in function print() setting the parameter file with the stream.

The content of io.StringIO() can be read in a string with the method io.StringIO.getvalue().

To execute a code dynamically use the built-in function exec.

The example below presupposes the use of three text files that together compose a script:

script.py1

texto = 'Hello, world!'

script.py2

def foo(s):
  print(f'foo {s}')

script.py3

foo(texto)

The python script that will read the three files, join its contents and dynamically execute the generated script:

import io

#Inicializa stream de texto a ser preenchida com conteúdo dos arquivos.
f = io.StringIO()

#Abre, lê e junta os conteúdos dos arquivos na memória.
with open('script.py1') as script:
  print(*script.readlines(), file=f)
with open('script.py2') as script:
  print(*script.readlines(), file=f)
with open('script.py3') as script:
  print(*script.readlines(), file=f)

#Obtem uma string com o conteúdo unificado dos arquivos.
arquivo = f.getvalue()
#Fecha a stream.
f.close()


#Executa o arquivo no contexto local.
exec(arquivo, globals(), locals())               #foo Hello, world!

Test the example on Repl.it

Browser other questions tagged

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