簡體   English   中英

為什么我的Python腳本無法通過命令行運行?

[英]Why is my Python script not running via command line?

謝謝!

def hello(a,b):
    print "hello and that's your sum:"
    sum=a+b
    print sum
    import sys

if __name__ == "__main__":
hello(sys.argv[2])

它對我不起作用,我感謝您的幫助!!! 謝謝!

在沒有看到錯誤消息的情況下,很難確切地說出問題出在哪里,但是有幾件事跳出來:

  • 如果__name__ ==“ __main__”后沒有縮進:
  • 您只需將一個參數傳遞給hello函數,它需要兩個參數。
  • sys模塊在hello函數外部的作用域中不可見。

可能更多,但再次需要錯誤輸出。

這是您可能想要的:

import sys

def hello(a,b):
    print "hello and that's your sum:"
    sum=a+b
    print sum

if __name__ == "__main__":
    hello(int(sys.argv[1]), int(sys.argv[2]))
  • 全局范圍內導入sys ,而不是在函數末尾導入。
  • hello發送兩個參數 ,其中一個是不夠的。
  • 將這些參數轉換為float ,以便可以將它們添加為數字。
  • 正確縮進 在python中,縮進確實很重要。

這將導致:

import sys

def hello(a, b):
    sum = a + b
    print "hello and that's your sum:", sum

if __name__ == "__main__":
    hello(float(sys.argv[1]), float(sys.argv[2]))

暫無
暫無

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

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