1

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?

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

You should include after the functions this:

this runs the program

if main == "name":# before and after 'main' and 'name' there are two under_scores! print "hi" etc...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.