Using python, how to find a different python script in a directory and then run it

Viewed 55

Using python, I need to find another python script file in a directory and then run it

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.

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?

3 Answers

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('py -3 ' + filepath)

for catch 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)
Related