我编写了一个python函数,它接受多个参数,我希望它从终端运行,但它不起作用。我做错了什么?
counting.py脚本:
def count (a, b):
word = False
a = " " + a + " "
b = " " + b + " "
result = 0
for i in range (len (a)-1):
if a[i] == " " and a[i+1] != " ":
word = True
result += 1
else:
word = False
for i in range (len (b)-1):
if b[i] == " " and b[i+1] != " ":
word = True
result += 1
else:
word = False
return result
if __name__ == "__main__":
count (a, b)
终端命令:
python counting.py count "hello world" "let's check you out"
答案 0 :(得分:1)
使用sys
模型,
添加此代码,sys.argv第一个参数是此文件名
import sys
if __name__ == "__main__":
a = sys.argv[1]
b = sys.argv[2]
count(a,b)
终端命令:
python counting.py "hello word" "let's check you out"
例如:
import sys
def count(s1, s2):
print s1 + s2
print sys.argv
count(sys.argv[1], sys.argv[2])
出:
python zzzzzzz.py“hello”“word”
['zzzzzzz.py', 'hello', 'word']
helloword
答案 1 :(得分:0)
a
和b
是count
的参数。您不能在该范围之外使用它们。您可以使用sys.argv
来访问命令行参数:
from sys import argv
if __name__ == "__main__":
print(count (argv[1], argv[2]))