2013-07-09 55 views
12

這是我的python腳本(hello.py):如何在Windows命令行中使用參數運行Python腳本

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

的問題是,它不能從Windows命令行提示符下運行,我使用這個命令: C:\ Python27> hello 1 1 但它不工作,不幸的是,可能有人請幫助

+1

請使用正確的代碼格式 – thibauts

+0

如果「hello.py」是在'PATH'目錄,並運行'你好1 1'沒有通過命令行參數,然後將.py文件關聯破碎。如果CMD或PowerShell未找到「hello.py」,則.PY不在「PATHEXT」中。你不需要運行'python hello.py 1 1'。這很煩人,因爲它需要使用hello.py的合格路徑或首先更改其目錄。 – eryksun

回答

7

要從命令行執行你的程序,你必須調用python解釋器,像這樣:

C:\Python27>python hello.py 1 1 

如果您的代碼駐留在另一個目錄中,則必須在PATH環境變量中設置python二進制路徑,以便能夠運行它。你可以找到詳細的說明here

+0

或者只是拼寫python my_full_path \ hello.py 1 1 – doctorlove

+0

非常感謝你,我也用這種方式,我定義了環境變量(PATH,path和pathext),沒有成功 – user2563817

+0

確保關閉並重新打開當您對PATH進行更改時使用的控制檯。 – thibauts

2

您的縮進被打破。這應該可以解決它:

import sys 

def hello(a,b): 
    print 'hello and thats your sum:' 
    sum=a+b 
    print sum 

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

很顯然,如果你把if __name__聲明的功能,它會永遠只能如果您運行的功能進行評估。問題是:所述陳述的要點是首先運行該功能。

+0

非常感謝你爲這個代碼,它的工作,但我想知道什麼是錯的,以及在哪裏可以找到更多的細節請,非常感謝你 – user2563817

+1

我告訴你什麼是錯的。 –

14
  • import sys out of hello function。
  • 參數應該轉換爲int。
  • 包含'的字符串字面應該被轉義或應該圍繞"
  • 您是否在命令行中使用python hello.py <some-number> <some-number>來調用程序?

import sys 

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

if __name__ == "__main__": 
    a = int(sys.argv[1]) 
    b = int(sys.argv[2]) 
    hello(a, b) 
+0

'進口'不在頂層 - 不推薦。應該放在'def hello'之前 – ElmoVanKielmo

+0

@ElmoVanKielmo,謝謝你的建議。我改變了代碼。 – falsetru

+0

在Python 2.7中不建議使用不帶圓括號的'print'。你應該瞄準與Python 3的兼容性;) – Agostino

1
import sys 

def hello(a, b): 
    print 'hello and that\'s your sum: {0}'.format(a + b) 

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

而且看到@thibauts回答有關如何調用Python腳本。

1

這裏都總結了以前的答案:

  • 模塊應的功能外進口。
  • hello(sys.argv [2])需要縮進,因爲它位於if語句中。
  • hello有2個參數,所以你需要調用2個參數。
  • 儘可能調用來自終端的功能,你需要調用Python的.py ...

的代碼應該是這樣的:

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

然後運行這個命令的代碼:

python hello.py 1 1 
相關問題