Reputation: 1692
So in my file1.py
, I have something like:
def run():
# Do something
print "Hi"
Now I want to use function run()
in another file.
from file1.py import run
However, when I execute the other file it also prints Hi
. How do I suppress this?
Upvotes: 1
Views: 53
Reputation: 11
You should include after the functions this:
if main == "name":# before and after 'main' and 'name' there are two under_scores! print "hi" etc...
Upvotes: 1
Reputation: 160677
Add the print "Hi"
in an if __name__ == "__main__"
clause.
When python imports modules it executes the code contained in them in order to build the module namespace. If you run the module as the main script the __name__
is going to get assigned to __main__
and the code inside the if
clause is going to get executed.
Since you're not running the script as the main script the __name__
gets assigned to the modules __name__
(in this case file1
) and as a result this test will not succeed and the print
statement is not going to get executed.
def run():
# Do something
if __name__ == "__main__":
print "Hi"
Upvotes: 2
Reputation: 3852
if you don't want Hi to be printed, simply delete from your file1.py
if you want Hi to be printed when run() is called, then indent it so that it belongs to the run() function.
Upvotes: 0