gpt4 book ai didi

python - 在终端中执行带有多个参数的python函数

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:34 25 4
gpt4 key购买 nike

我编写了一个带有多个参数的 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" 

最佳答案

使用sys模型,添加这段代码,sys.argv第一个参数就是这个文件名

import sys
if __name__ == "__main__":
a = sys.argv[1]
b = sys.argv[2]
count(a,b)

终端命令:pythoncount.py“hello word”“让我们来看看你”例如:

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

关于python - 在终端中执行带有多个参数的python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com