首页 > 解决方案 > 在python中导入包含“if __name__ == '__main__':”的python程序

问题描述

我有两个 python 脚本,其中一个必须编写json( file1.py) ,另一个 ( file2.py) 是 import file1

我的 python 脚本file1.py已成功执行,但是当我尝试导入时file2.py它不起作用,因为它包含if __name__ == '__main__':

文件1.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)

文件2.py:

import file1
from file1 import demo

如果我运行我file2.py的只是像这样生产

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

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

有没有可能在 file2.py 中导入 file1.py

标签: pythonimport

解决方案


您可以改为创建一个类,将其放入 file1.py 并像这样导入它

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)



推荐阅读