Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

simultaneous - Run another python file from a python program?

I want a peice of code which would run another python file. I would like to be able to run the 2 files simultaneously.

print('Hello World') 

run ('this file') #obviously not real code

print('Hello World Agian') #continue with program

i really need the programs to run simultaneously. I dont mind downloading a library to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update from this comment:

You can try sending a bash command using this code:

import subprocess
process = subprocess.Popen("python script1.py & python script2.py &".split(), stdout=subprocess.PIPE)
output, error = process.communicate()

Bash command from this question, code to run the bash from this question. You need 3 programs: the first to run this code, the second (script1.py) and third (script2.py) will be run by the program.


Original:

I made a class for importing files, although it might be overkill for what you want. You could use just a

import filename

, but if you need to import files with user-inputted names and reimport some of them, you can use this class below:

from importlib import __import__, reload
from sys import modules

class Importer:
    libname = ""
    import_count = 0
    module = None

    def __init__(self, name):
        self.libname = name
        self.import_count = 0

    def importm(self):
        if self.libname not in modules:
            self.module = __import__(self.libname)
        else:
            self.module = reload(self.module)
        self.import_count += 1

# test out Importer

importer = Importer("mymodule")

""" mymodule.py

print("Hello")

"""

importer.importm() # prints Hello
importer.importm() # prints Hello
importer.importm() # prints Hello (again)

print(importer.import_count)

I made this class some time ago for a question that was deleted (10k to view my answer).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...