[英]Using python, how to find a different python script in a directory and then run it
Using python, I need to find another python script file in a directory and then run it使用 python,我需要在一个目录中找到另一个 python 脚本文件,然后运行它
system = input("Enter system name: ")
for filename in listdir(directory):
if filename.find(system + "_startup") != -1 and filename.endswith(".py"):
# import and run specific startup script
I know how to find and open a file normally, and I know how to call one python script from another script, but I don't really know how to bridge the gap here.我知道如何正常查找和打开文件,也知道如何从另一个脚本调用一个 python 脚本,但我真的不知道如何弥补这里的差距。
Each system I'm working with will have a different "startup" script which runs.我正在使用的每个系统都会有一个不同的“启动”脚本运行。 I don't want to have to import every single startup file I have into my main script (there's a lot of startup scripts) only the specific one for the system of interest.
我不想将我拥有的每一个启动文件都导入到我的主脚本(有很多启动脚本)中,只导入感兴趣系统的特定文件。 Is there a way for me to achieve this without importing all the startup files?
有没有办法让我在不导入所有启动文件的情况下实现这一目标?
If all you need to do is execute the script, one option is to spawn a new process:如果您需要做的就是执行脚本,则一种选择是生成一个新进程:
import subprocess
subprocess.run(["python3", filename])
Why not use os.system to execute the command in a subshell?为什么不使用 os.system 在子 shell 中执行命令?
os.system('py -3 ' + filepath)
for catch output bash用于捕捉 output bash
import subprocess
from subprocess import Popen
system = input("Enter system name: ")
for filename in listdir(directory):
if filename.find(system + "_startup") != -1 and filename.endswith(".py"):
p = Popen(["python3",filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = p.communicate()
# catch output bash
print(output)
# catch erro bash
print(errors)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.