![](/img/trans.png)
[英]How do I run a python script on pypy3 without using the command line on windows 10?
[英]How do I run Python script using arguments in windows command line
這是我的 python hello.py
腳本:
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
但不幸的是它沒有用,有人可以幫忙嗎?
import sys
。'
字符串文字應該被轉義或者應該被"
包圍。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)
我發現這個線程正在尋找有關處理參數的信息; 這個簡單的指南太酷了:
import argparse
parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")
args = parser.parse_args()
opt1_value = args.opt1
opt2_value = args.opt2
運行如下:
python myScript.py --opt2 = 'hi'
以下是總結的所有以前的答案:
代碼應如下所示:
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
要從命令行執行程序,您必須調用 python 解釋器,如下所示:
C:\Python27>python hello.py 1 1
如果您的代碼位於另一個目錄中,則必須在 PATH 環境變量中設置 python 二進制路徑才能運行它。 您可以在此處找到詳細說明。
你的縮進被打破了。 這應該解決它:
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__
語句放在函數中,則只有在運行該函數時才會對其進行評估。 問題是:所述語句的重點是首先運行該函數。
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 腳本的答案。
代碼中有不止幾個錯誤。
由於您沒有為任何函數參數定義任何默認值,因此有必要在調用函數時傳遞兩個參數 --> hello(sys.argv[2], sys.argv[2])
import sys def hello(a,b): print ("hello and that's your sum:") sum=float(a)+float(b) print (sum)
if __name__ == "__main__": hello(sys.argv[1], sys.argv[2])
此外,使用“C:\Python27>hello 1 1”運行代碼看起來不錯,但您必須確保該文件位於 Python 知道的目錄之一(PATH 環境變量)。 因此,請使用完整路徑來驗證代碼。 就像是:
C:\Python34>python C:\Users\pranayk\Desktop\hello.py 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.