簡體   English   中英

帶有hello.py追溯的Python錯誤

[英]Python error with hello.py traceback

我是Python的新手。 我的hello.py命令有問題。 它給了我以下錯誤:

C:\Users\Admin>python hello.py
Traceback (most recent call last):
    File "hello.py", line 1 in <module>
        if _name_ == "_main_":
NameError: name '_name_' is not defined

嘗試在名稱和主名稱前后使用2個下划線,因此:

__name__

__main__

嘗試將其放在您的hello.py

def myfunction():
   print "hello!"

if __name__ == "__main__":
   myfunction():

換一種說法

將您在hello.py腳本中包含的代碼封裝在函數包裝中(上例中的myfunction() )。 現在, 從命令行執行hello.py時, if __name__ == "__main__":部分將調用myfunction()


這是另一種方式

如果要在另一個Python腳本中將hello.py import hello.py為Python模塊,請說另一個Python.py。 將一個空文件放置在與hello.py相同的目錄中,該hello.py的名稱恰好是__init__.py 然后在anotherPython.py中編寫:

import hello
hello.myfunction()

然后應該打印“你好!” 在Python中執行時。

暫無
暫無

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

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