1

I want to import variables from another program using the from import function. Sample Code:

script1:
c=1
print('hello')

script2:
from script1 import c

When I run this my response is:

hello
10

I wanted to know if it is possible to make this run with only the variable c being shown.

A Bo
  • 45
  • 2
  • 5

2 Answers2

7

Move any code you don't want to run on import into the if __name__ == '__main__' block.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You don't, that's how it works. If you want some code to not run, then move it to the section __main__:

import statements
code_that_runs()

if __name__ == '__main__':
    code_that_will_not_run_from_import()
Diracx
  • 61
  • 10
tglaria
  • 5,678
  • 2
  • 13
  • 17