Question

I have 2 python files. file1.py and file2.py

file1.py

print "file1"

file2.py

import file1 print "file2"

and when i run file2,the output is

file1 file2

The question may seem little naive but i want to know what exactly is happening here.

Thanks in Advance.

Was it helpful?

Solution

Yes. When importing a file it is being run. To avoid this, file1.py can be:

if __name__=='__main__':
    print 'file1'

And then the text will be printed only if file1.py is the main file being run directly.

OTHER TIPS

In a sense yes. When you import a file, you will run all the script and you will also initialize all the methods.

To ensure that code is only run when the file is run directly and not when it is imported. You should put all your main code in main() and do it as:

def main():
    #all your main code here

if __name__ == '__main__':
    main()

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the import statement is defined as a call to the import() function, with the appropriate arguments. The return value of import() is used to perform the name binding operation of the import statement. See the import statement for the exact details of that name binding operation.

import file using python

To print 'file2' your code, you need to pass it as a command to the Python interpreter,

python myscript.py

there's no main() function that gets run automatically, so the main() function is implicitly all the code at the top level, and call if __name__ == "__main__"

How main does in python

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top