2

I am trying to read value of a variable from one file to another file, but I am not able to read only the value of variable. See sample script of two files. Most the forms gives information regarding access of variables in another file. When i implement those methods I am not getting as what i am expecting.

file name: t1.py

print 'Hello'
a=123
print 'welcome'

file name: t2.py

from t1 import a
print 'Python'
print a

When I run the above script output I am getting is

Python
Hello
Welcome
123

But I am expecting the output must be:

Python
123

Is there any way for getting only content of single variable in a big python script.

krocks
  • 199
  • 1
  • 2
  • 15
  • Also, [Why is Python running my module when I import it, and how do I stop it?](http://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) – vaultah Jan 06 '16 at 12:15
  • @vaultah Here my python running and displaying the print statements of one file in another file. – krocks Jan 06 '16 at 12:36
  • Yes, because Python executes top level stuff in a module that needs to be imported. The workaround is presented in linked question(s). – vaultah Jan 06 '16 at 12:37
  • @vaultah .. i am unable to understand that link... can you say is there any way to read value of one variable in a script having multiple print statements. – krocks Jan 06 '16 at 12:53
  • Simply move those print statements inside the `if` block: `if __name__ == "__main__": ... print statements ...` There isn't a clean way to do this without modifying your module. – vaultah Jan 06 '16 at 12:55

0 Answers0