简体   繁体   中英

Python - How to call code from an external file

I have revised this question to make it much more simple.

I am running a program in python 3.x . I want this program to open a file name example.py and run the code inside it. This is the contents of the file:

#example1.py
print('hello world')

#example2.py
    print('hello world 2')

#main.py
someMagicalCodeHere(executes example2.py)
#prints hello world

I need to do this without it being an imported file.

The problem with imported files is they are declared beforehand in the main.py. My main.py will be creating example1.py, example2.py etc and filling them with code, and then later referencing back to them as needed. There may be thousands or millions.

This is part of a large project that we are trying to switch over to a new language. We don't know python yet, and we need this concept to be viable to continue learning the language.

I have tried exec(example.py)

I have tried with open('example.py', 'r') as ex: ex.read()

Thanks in advance for the answer, and thanks for all who have answered thus far.

I'm assuming you have some kind of a function that converts strings to such answers, or perhaps a dictionary. Otherwise the solution to this problem would be beyond the scope of current progress in NLP.

def ask_question_and_get_response(question=None): answer = input(question) return answer

I must also assume that you have a way to convert the original question, such as "What is your name?" , to one that the user may in turn ask your bot, "What is my name?" . Let that function look like what follows:

def get_reflex_question(question):
    <your implementation>
    return reflex_question

With both of these in hand, we can create a file (if one doesn't already exist), and write what can be interpreted as Python code to it.

def make_code(answer, reflex_question)
    with open("filename", "a") as file:
        file.write("\n")
        file.write("if userBoxAsks == %s:\n\t" % (reflex_question))
        file.write("print(answer)")

Which will output code to a file of your naming. To run that file, you could use the subprocess module (read documentation), or simply import this file of yours as a module itself. Whenever you update the file, you could reload the import so that the new code runs too. In Python3.x, you can do importlib.reload(filename) to refresh the import.

Alright after much deliberation, hunting and searching, I discovered through experimentation, found the answer to my own question.

#c:\\one.py
print('hello world')

#c:\\main.py
import os.path


filename = "c:\\one.py"

if not os.path.isfile(filename):
    print ('File does not exist.')
else:

    with open(filename) as f:
        content = f.read().splitlines()

    for line in content:
        exec(line)

Returns (without quotes) 'Hello World'

Note that these solutions are not secure and considered risky. So obviously meant for play/test purpose

Python 2:

execfile('example2.py') 

Python 3:

with open('example2.py') as f:
    exec(f.read())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM