-1

I have two files: file1.py and file2.py

file1.py

print("34343433")

def print_hello():
    print("Hello")

file2.py

from file1 import print_hello

print_hello()

the output of file2 is:

34343433
Hello

I just want to have it print only the "Hello" portion.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Does this answer your question? [Why is Python running my module when I import it, and how do I stop it?](https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) – wjandrea Oct 21 '22 at 02:20

2 Answers2

0

When you import a file in Python, all code in the file is run (even in partial imports), including the print statement you had. To remove the extra numbers, you have two options:

1: Remove the code

#file1.py
def print_hello():
    print("Hello")

2: Put it into its own function

#file1.py
def print_nums():
    print("22132322432")#Call this with file1.print_nums()
def print_hello():
    print("Hello")

In both of these cases, running file2.py will only produce the output Hello. If you want a way to detect if file1 is being imported, see Alex Grounds' answer. Hope this solves your issue

Enderbyte09
  • 409
  • 1
  • 5
  • 11
0

As Enderbyte mentioned, when you import file1 (or for that matter from file1 import print_hello), all code in that file is run. However, there is a way to check if this file is being run directly, or being imported instead:

def print_hello():
    print("Hello")

if __name__ == '__main__':
    print("34343433")
    # add other code if desired

Then print("34343433") will only run if file1 is invoked directly via python file1.py. When it's imported, that print statement will not execute.

Alex Grounds
  • 256
  • 2
  • 12