Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python,如何在目录中找到不同的python脚本,然后运行它_Python - Fatal编程技术网

使用python,如何在目录中找到不同的python脚本,然后运行它

使用python,如何在目录中找到不同的python脚本,然后运行它,python,Python,使用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 我知道如何正常地查找和打开

使用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
我知道如何正常地查找和打开文件,我知道如何从另一个脚本调用一个python脚本,但我真的不知道如何弥合这一差距


我使用的每个系统都会有一个不同的“启动”脚本。我不想把我所有的每个启动文件都导入我的主脚本(有很多启动脚本),只导入感兴趣的系统的特定文件。我有没有办法在不导入所有启动文件的情况下实现这一点?

如果您只需要执行脚本,一个选项是生成一个新进程:

import subprocess

subprocess.run(["python3", filename])

为什么不使用os.system在子shell中执行命令

os.system('py -3 ' + filepath)
用于捕获输出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)