Is there a way to import items from a file without

2019-09-15 16:40发布

问题:

This question already has an answer here:

  • Why is Python running my module when I import it, and how do I stop it? 9 answers

I have two files, file1 and file2.

files 2 is this:

print "Why is this printing"

var = 7

file 1 is this:

from file2 import var

print var

When I run this code, it outputs the following:

>>>Why is this printing
>>>7

Is there a way I can obtain var from file2 without running the code above the declaration of var?

回答1:

If you don't want code to run when a module is imported, put it in a function:

def question():
    print "Why is this printing"

If you want the function to run when the module is passed to the python interpreter on the command line, put it in a conditional expression block:

if __name__ == '__main__':
    question()

e.g.

c:/> python file2.py
Why is this printing


回答2:

You can use standard

if __name__ == "__main__":

guard to protect some lines from executing on importing. This condition is satisfied only if you run that particular file, not import it.



标签: python import