Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Python script using arguments in windows command line

This is my python hello.py script:

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

The problem is that it can't be run from the windows command line prompt, I used this command:

C:\Python27>hello 1 1 

But it didn't work unfortunately, may somebody please help?

like image 995
user2563817 Avatar asked Jul 09 '13 09:07

user2563817


People also ask

How do I run a Python script from an argument in Windows?

You can use the command line arguments by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.

How do I run a command line argument in Windows?

You can use wt.exe to open a new instance of Windows Terminal from the command line. You can also use the execution alias wt instead. If you built Windows Terminal from the source code on GitHub, you can open that build using wtd.exe or wtd .


2 Answers

  • import sys out of hello function.
  • arguments should be converted to int.
  • String literal that contain ' should be escaped or should be surrouned by ".
  • Did you invoke the program with python hello.py <some-number> <some-number> in command line?

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) 
like image 125
falsetru Avatar answered Oct 09 '22 02:10

falsetru


I found this thread looking for information about dealing with parameters; this easy guide was so cool:

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 

run like:

python myScript.py --opt2 = 'hi' 
like image 43
hestellezg Avatar answered Oct 09 '22 03:10

hestellezg