0

I have a file directory like so..

myScript.py

--Projects

----Test

------test0.py

------test1.py

------test2.py

From myScript.py I am trying to use a for loop to iterate over the files in the project directory and run the main module of each.

import os
from os import listdir
from os.path import isfile, join


def main(project_loc="Test"):
    print('I am main of main')
    current_dir = os.getcwd()
    project_dir = os.path.join(current_dir, 'Projects', project_loc)
    onlyfiles = [f for f in listdir(project_dir) if isfile(join(project_dir, f))]
    count = 0 
    for file in onlyfiles:
        file_name = os.path.join(project_dir, file).rstrip('.py')
        print('File' + str(count), file_name)
        new_module = __import__(file_name)
        #new_module.main()                 #Run module I just imported
        count += 1
    print(modules)

    return


if __name__ == "__main__":
    main()

myScript.py above

def main():
    print('I am main of file 0')
    return False


if __name__ == "__main__":
    main()

test0.py above(rest are similar)

It is not an option to just import those three files because there is more then just them.

It is also not an option to use an additional libraries. It must be done using only modules already packaged with python

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
John Salzman
  • 500
  • 5
  • 14

1 Answers1

0

The problem is that __import__ is being called with the path to the files as a parameter (eg ~/directory/Projects/Test/test0). Instead __import__ takes a name parameter that should look something like Projects.Test.test0.

Now, to run the scripts you want, there are various options. Please see Run a Python script from another Python script, passing in arguments

araraonline
  • 1,502
  • 9
  • 14
  • I've made this community wiki because I don't think this is a quality answer. The actual substance is in the question linked. – araraonline Jun 18 '19 at 00:53