簡體   English   中英

在 python 中導入包含“if __name__ == '__main__':”的 python 程序

[英]import python program which contains “if __name__ == '__main__':” in python

我有兩個 python 腳本,其中一個必須編寫jsonfile1.py ),另一個( file2.py )是導入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

您可以改為創建一個 class,將其放入 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)


你說它不起作用是什么意思? 究竟會發生什么? 如果 file2.py 純粹是這樣,它當然不會運行,因為你沒有運行任何東西。 if __name__ == '__main__':意味着只有直接運行而不是導入的東西才會運行。

當您在if __name__ == '__main__'下編寫內容時,它們會在我們的腳本從命令行運行時執行。 如果您在其他 python 腳本中導入腳本,這部分將不會執行(請參閱此詳細說明以了解原因)。

能夠在另一個腳本中導入代碼的一種方法是將其放入 function 中,如下所示:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM