【问题标题】:Python program with main() method does not run具有 main() 方法的 Python 程序无法运行
【发布时间】:2018-04-11 01:25:25
【问题描述】:
def main():
   names = []
   for line in ins:
       number_strings = line.split() # Split the line on runs of whitespace
       data.append(numbers_strings) # Add the "row" to your list.
       print(data)

我尝试使用此代码打印一个看起来像这样的文本文件

name num1 num2 C/N

我正在尝试打印它,但是当我运行命令“python3 file.py”时没有输出。而不是打印我放入的文件的内容

【问题讨论】:

    标签: python


    【解决方案1】:

    与 C 不同,python 中的执行不是从 main 方法开始的,因为 python 遵循自上而下的方法。您需要做的是明确调用main 方法以使其运行。

    def main():
        ...
    
    main()
    

    如果您希望main 方法仅在通过脚本调用时运行(而不是在导入时),请指定它应该在__name__ 下运行:

    def main():
        ...
    
    if __name__ == '__main__':
        main()
    

    欲了解更多信息,请阅读

    【讨论】:

      【解决方案2】:

      如果您只想执行该代码,您可以忘记主函数,只需编写您的代码

      names = []
         for line in ins:
             number_strings = line.split() # Split the line on runs of whitespace
             data.append(numbers_strings) # Add the "row" to your list.
             print(data)
      

      如果您确实想使用主要功能,请遵循社区 wiki 答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2021-12-19
        • 2015-07-24
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 2013-03-03
        相关资源
        最近更新 更多