Run python file string

0

I want to run several similar programs one after the other in the terminal.

archivo1.py
archivo2.py
archivo3.py

I must not unite the 3 files and create 1 only with the functions of the three, what I am looking for is that I can create a new file with a function that calls those 3 files to be executed!

A possible solution is this but it does not work for me:

import archivo1
import archivo2
import archivo3
if __name__ == "__main__":

I do not know what to put after the colon and if the files do not go with the .py and quotes or something

Thank you very much

Greetings

    
asked by Martin Bouhier 05.10.2017 в 23:02
source

2 answers

2

The simplest way is to use os.system()

import os

os.system("python archivo1.py")
os.system("python archivo2.py")
os.system("python archivo3.py")

But, another way that offers more control is using subprocess which is worth It's worth seeing the documentation

import subprocess

process1 = subprocess.Popen(['python', 'archivo1.py'])
process2 = subprocess.Popen(['python', 'archivo2.py'])
process3 = subprocess.Popen(['python', 'archivo3.py'])
    
answered by 05.10.2017 в 23:20
0

The method proposed by Patricio allows creating a process for each of the modules. It is a good option if you are only going to execute the script. Remember to give execution permission to the script for the appropriate user.

You can also simply import them. This will simply execute the content of each script sequentially in the order of the imports:

main.py :

import archivo1
import archivo2
import archivo3

The file must be in the same directory as the three previous files.

The code of each module is executed except the one you have inside:

if __name__ == "__main__":

To know more about the previous sentence you can see the following publication:

What is if __name__ == "__main__" :?

Edit:

The problem is that including the "$" character in the name of your module is not a valid identifier and can not be imported. As a general rule you should not name your modules with invalid identifiers , however, you can import them in the following way:

archivo1 = __import__('archivoMW$1')
archivo2 = __import__('archivoMW$2')
archivo3 = __import__('archivoMW$3')

Or simply:

__import__('archivoMW$1')
__import__('archivoMW$2')
__import__('archivoMW$3')

I repeat that the ideal would be to name the modules with valid identifiers.

    
answered by 05.10.2017 в 23:30