简体   繁体   中英

Why does importing a file that contains a print() cause the output to be printed?

Consider the following Python files

file_one.py:

text = ("Sample text")
print(text)

file_two.py:

import file_one

Running python file_two.py gives the following output:

Sample Text

I was wondering why file_two automatically prints the output of file_one when it has been imported. I thought you may need to specifically call it to print out the text like print(file_one.text) .

Similarly, in theory, is this any different from importing libraries such as random or pandas etc? As in, if they have a line that says print("hello") , hello will be printed automatically in the output of the module that imports it?

It's because files are run when imported.

This might help https://www.pythonmorsels.com/importing-module-runs-code/

When you import a file, everything at the top level of the file (that isn't part of a class or function) is run immediately.

That includes imports of other modules.

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