-1

I have two python scripts one of whic has to write a json (file1.py) and another one(file2.py) is to import file1.

My python script file1.py has executed successfully, but when I try to import in file2.py it doesn't work as it contain if __name__ == '__main__':

file1.py

def demo(opt,streamPixel):
    #some functions

if __name__ == '__main__':
    streamPixel = "{\"type\":\"FeatureCollection\",\"features\":["
    #parser = argparse.ArgumentParser()
    Transformation= 'TPS'
    FeatureExtraction = 'ResNet'
    SequenceModeling = 'BiLSTM'
    Prediction = 'Attn'
    num_fiducial = 20
    input_channel = 1
    output_channel = 512
    imgH = 72
    imgW =320
    hidden_size = 256
    rgb = False
    batch_max_length = 25
    character = '01'
    sensitive =True
    #PAD = True
    image_folder ='D:/work/source_code/VIC_OCR/cropped'
    workers = 4
    batch_size= 192
    num_class = 4
    saved_model = 'D:\\SARIGHA\\source_code\\saved_models\\TPS-ResNet-BiLSTM-Attn-Seed323\\best_accuracy.pth'

    opt = None

    """ vocab / character number configuration """
    if sensitive:
        character = string.printable[:-6]  # same with ASTER setting (use 94 char).

    cudnn.benchmark = True
    cudnn.deterministic = True
    num_gpu = torch.cuda.device_count()

    demo(opt,streamPixel)

file2.py:

import file1
from file1 import demo

if I run my file2.py is simply produce like this

(victoria) D:\work\source_code\textReg\imageOrientation>python file2.py

(victoria) D:\work\source_code\textReg\imageOrientation>

is there is any possible to import file1.py in file2.py

Tasnuva Leeya
  • 2,515
  • 1
  • 13
  • 21
suji
  • 407
  • 4
  • 17
  • 3
    The whole point of using `if __name__ == '__main__':` is that you do **not** want that code to execute simply when you import the module. You would use it for example where a module contains a mixture of reusable code that you might want to import into other modules plus other code (maybe test code) that you only want to execute when the module is run as a main program. To run it as a main program, you would have to use something like `subprocess.Popen` or `os.system` to run `python file1.py`. – alani Aug 04 '20 at 10:15
  • @alaniwi by using yours idea 'os.system' works perfectly, thank you – suji Aug 04 '20 at 11:42

3 Answers3

1

You could instead create a class, put it in file1.py and import it like this

from file1.py import pixelModel

pixelModel = pixelModel()
class pixelModel():
# all your variables you have mentioned in main

def __init__(sensitive):
    self.sensitive = sensitive
    if sensitive:
        character = string.printable[:-6]
    cudnn.benchmark = True
    cudnn.deterministic = True
    self.num_gpu = torch.cuda.device_count()

    demo(opt,streamPixel)


Dustin
  • 483
  • 3
  • 13
  • looking good, but there is any alternatives instead using class – suji Aug 04 '20 at 11:06
  • You can actually just omit the if __name__.. part, Python doesn't need a "main" like other languages do. But it will automatically run on import, so keep that in mind. – Dustin Aug 04 '20 at 11:25
  • but I cannot omit if name, if I do so it produce freeze_support() error in it – suji Aug 04 '20 at 11:27
  • I tried using 'class' but class cannot import in file2.py – suji Aug 04 '20 at 11:35
  • Could you provide more info on what didn't work? Code would be great! – Dustin Aug 04 '20 at 14:07
  • I don't know clearly as I said above, when I run my file2.py it doesn't read a single line of a program which are comes under main – suji Aug 05 '20 at 04:59
  • In file1.py, there is nothing but the class. No `if __name__=="main"` or something else. In file2.py, you begin with `from file1.py import pixelModel` and initialize it at any pixelModel = pixelModel()point, for example in the scope of `if __name__=="main":`, with – Dustin Aug 05 '20 at 09:37
0

What do you mean by it doesn't work? What exactly happens? If file2.py is purely just that, of course it won't run, because you're not running anything. if __name__ == '__main__': means that that stuff will only run if it's being run directly, rather than imported.

rak1507
  • 392
  • 3
  • 6
0

When you write stuff under if __name__ == '__main__', they get executed when our script is run from the command line. If you import your script in an other python script, this part won't get executed (see this well detailed explanation to understand why).

One way to be able to import the code in another script would be to put it in a function like this:

file1.py:


def myfunction():
    # Do what you want here
    print('This is my function in file1')

if __name__ == '__main__':
    myfunction()

file2.py:

from file1 import myfunction

if __name__ == '__main__':
    myfunction()
bastantoine
  • 582
  • 4
  • 21
  • is there any alternative method? coz I don't want to use if __name__ == '__main__': in my file2.py – suji Aug 04 '20 at 11:03
  • Oh yes of course, as long as you have `myfunction` imported in `file2.py`, you can use it wherever you want. – bastantoine Aug 04 '20 at 12:00