[英]Run another python file from a python program?
I want a peice of code which would run another python file.我想要一段代码来运行另一个 python 文件。 I would like to be able to run the 2 files simultaneously.
我希望能够同时运行 2 个文件。
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.
我不介意下载图书馆来做到这一点。
Update from this comment :从此评论更新:
You can try sending a bash command using this code:您可以尝试使用以下代码发送 bash 命令:
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 .此问题中的 Bash 命令,此问题中运行 bash 的代码。 You need 3 programs: the first to run this code, the second (
script1.py
) and third ( script2.py
) will be run by the program.您需要 3 个程序:第一个运行此代码,第二个 (
script1.py
) 和第三个 ( script2.py
) 将由程序运行。
Original :原文:
I made a class for importing files, although it might be overkill for what you want.我制作了一个 class 用于导入文件,尽管对于您想要的东西来说它可能有点矫枉过正。 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: ,但如果您需要导入用户输入名称的文件并重新导入其中一些文件,则可以使用下面的 class:
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 ).前段时间我做了这个 class 来解决一个被删除的问题(10k 查看我的答案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.