简体   繁体   中英

Executing python functions with multiple arguments in terminal

I have written a python function which takes multiple arguments and i want it to run from terminal but it's not working. what am I doing wrong?

counting.py script:

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) 

terminal command:

    python counting.py count "hello world" "let's check you out" 

useing sys model, add this code, the sys.argv first parameter is this file name

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

terminal command: python counting.py "hello word" "let's check you out" ex:

import sys
def count(s1, s2):
    print s1 + s2

print sys.argv
count(sys.argv[1], sys.argv[2])

out:

python zzzzzzz.py "hello" "word"

['zzzzzzz.py', 'hello', 'word']
helloword

a and b are the arguments of count . You cannot use them outside that scope. You could instead use sys.argv to access the commandline arguments:

from sys import argv
if __name__ == "__main__":
    print(count (argv[1], argv[2]))

As suggested by others using sys :

from sys import argv

def count(a, b):
    return len(a.split(" ")) + len(b.split(" "))

if __name__ == "__main__":

    a = argv[1]
    b = argv[2]
    
    word_count = count(a, b)
    print(word_count)

Or , you could use the built-in module argparse . In case you ever have a more complex script taking arguments from the console.

import argparse

def count(a, b):
    return len(a.split(" ")) + len(b.split(" "))

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Word Count")
    parser.add_argument("-a", type=str, help="First Sentence")
    parser.add_argument("-b", type=str, help="Second Sentence")
    args = parser.parse_args()
    
    word_count = count(args.a, args.b)
    print(word_count)

Execute your script with python counting.py -a "hello world" -b "let's check you out" .

And if you execute python counting.py -h , you'll get a nicely formatted help for the users:

usage: counting.py [-h] [-a A] [-b B]

Word Count

optional arguments:
  -h, --help  show this help message and exit
  -a A        First Sentence
  -b B        Second Sentence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM