简体   繁体   中英

How to call function from another .py file in python?

I am trying to call a function 'myfunction()' defined in another py file 'file2.py' in same directory using below code

from file2 import *

myfunction()

Unfortunately, its executing my function twice. The import statement is also executing the function. Any insights on how to avoid this?

Probably you are calling inside your file2.py your function myfunction()

when you do

from file2 import *

you are loading every definitions (class, def, etc), and of course, every function called inside that .py.

To avoid this problem you can call your function myfunction() in your file2.py inside this scope:

if __name__ == '__main__':
    myfunction()

in this way it will not be executed when imported, but only if the file2.py is executed directly:

python3 file2.py
#File name = file2
class file3:
   def method():
      print ("printing statement")
      return "Hello world"

Main file name file1.py

from file2 import *
print(file3.method())

You can define function and write return statement to avoid extra printing

Check your file2 and look for anything with myfunction() in it. If there is something like it, just remove it.

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