How to call a function stored in another file from a Python program?

前端 未结 5 1921
故里飘歌
故里飘歌 2021-01-07 02:44

If I have a text file that contains a python function definition, how can I make the function call from another Python program. Ps: The function will be defined in the Pytho

5条回答
  •  执念已碎
    2021-01-07 03:17

    You are looking for the exec keyword.

    >>> mycode = 'print "hello world"'
    >>> exec mycode
    Hello world
    

    So if you read your text file as text (assuming that it only contains the function) like:

    test.txt:

    def a():
        print "a()"
    

    test.py:

    mycode = open('test.txt').read()
    exec mycode # this will execute the code in your textfile, thus define the a() function
    a() # now you can call the function from your python file
    

    Link to doc: http://docs.python.org/reference/simple_stmts.html#grammar-token-exec%5Fstmt

    You may want to look at the compile statement too: here.

提交回复
热议问题