2

I want to import a python script in to another script.

$ cat py1.py
test=("hi", "hello")

print test[0]

$ cat py2.py
from py1 import test

print test

If I execute py2.py:

$ python py2.py 
hi
('hi', 'hello')

Can I anyway mute the first print which is coming from the from py1 import test?

I can't comment the print in py1, since it is being used somewhere else.

erip
  • 16,374
  • 11
  • 66
  • 121

4 Answers4

5

py1.py use an if __name__=="__main__":

So like your py1.py would look like:

def main():
    test=("hi", "hello")

    print test[0]

if __name__=="__main__":
    main()  

This will allow you to still use py1.py normally, but when you import it, it won't run the main() function unless you call it.

This explains what's going on

MooingRawr
  • 4,901
  • 3
  • 24
  • 31
4

Simply open the /dev/null device and overwrite the sys.stdout variable to that value when you need it to be quiet.

import os
import sys

old_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")

from py1 import test

sys.stdout = old_stdout
print test
Axel Isouard
  • 1,498
  • 1
  • 24
  • 38
  • 1
    `os.devnull` thats what i was looking for eariler when i answered almost identically just after you posted your solution(I deleted mine) – Joran Beasley Oct 17 '16 at 13:32
1

You might want to consider changing the other script to still print when its run 'in the other place' - if you're running py1 as a shell command, try to make sure all "executable statements" in a file are inside a block.

if __name__ == "__main__":
    print test

(see What does if __name__ == "__main__": do?)

This would fix the underlying issue without having you do weird things (which would be redirecting the standard out, and then putting it back etc), or opening the file and executing line by line on an if block.

Community
  • 1
  • 1
Jmons
  • 1,766
  • 17
  • 28
  • not sure why the downvote as this is a pretty reasonable solution (I guess because its basically the same as the other solution..) – Joran Beasley Oct 17 '16 at 13:33
  • And if I had typed faster and not looked up references, I would have beaten you all.... Ahh well – Jmons Oct 17 '16 at 13:36
  • meh it happens to everyone ... (I had to delete an answer of mine since someone posted the same solution 10 seconds before me) – Joran Beasley Oct 17 '16 at 13:37
  • what do i do.. delete? leave this conversation for prosperity? Move on and just forget about it? – Jmons Oct 17 '16 at 13:46
1

You could implement this functionality with methods:

py1.py

test=("hi", "hello")

def print_test():
    print(test)

def print_first_index():
    print(test[0])

py2.py

import py1
py1.print_test()

As MooingRawr pointed out, this would require you to change whichever classes use py1.py to import it and call the py1.print_first_index() function which may not be to your liking.

Nanor
  • 2,400
  • 6
  • 35
  • 66