简体   繁体   中英

Why is my Python script not running via command line?

Thanks!

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

It does not work for me, I appreciate the help!!! Thanks!

Without seeing your error message it's hard to say exactly what the problem is, but a few things jump out:

  • No indentation after if __name__ == "__main__":
  • you're only passing one argument into the hello function and it requires two.
  • the sys module is not visible in the scope outside the hello function.

probably more, but again, need the error output.

Here's what you might want:

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]))
  • Import sys in global scope , not in the end of the function.
  • Send two arguments into hello , one is not enough.
  • Convert these arguments to floats , so they can be added as numbers.
  • Indent properly. In python indentation does matter.

That should result in:

import sys

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

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

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