Python包含main()方法的程序无法运行。

20 浏览
0 Comments

Python包含main()方法的程序无法运行。

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\"时,没有输出。而不是打印我输入的文件内容。

admin 更改状态以发布 2023年5月19日
0
0 Comments

如果您只想执行该代码,可以不考虑主函数,直接编写您的代码。\n

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)

\n如果您确实想使用主函数,请参考社区维基答案。

0
0 Comments

不像 C 语言,Python 不是从 main 方法开始执行的,而是采用自上而下的方法。你需要显式调用 main 方法才能运行它。

def main():
    ...
main()


如果你希望 main 方法只在通过脚本调用时运行(而不是被导入时运行),需要指定它应该在哪个 __name__ 下运行:

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

更多信息,请阅读:

0