Is There A Way To Import Items From A File Without Running All Of The Code In That File In Python
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 fo
Solution 1:
If you don't want code to run when a module is imported, put it in a function:
defquestion():
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 isthis printing
Solution 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.
Post a Comment for "Is There A Way To Import Items From A File Without Running All Of The Code In That File In Python"