I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?
code:
import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)
Error:
Traceback (most recent call last):
File "C:/pythonprogram/add.py", line 4, in
n=int(sys.argv[1])
IndexError: list index out of range
Your program is expecting two command line arguments.
sys.argv is a list of command line arguments. The error IndexError: list index out of range is telling you that you tried to get list item number 2, (with index 1), but the list doesn't have that many values.
You can reproduce that error in the shell:
>> alist = ['Item 0']
>> print(alist[1])
Since alist only has item with index 0 requesting items with higher indexes will cause that error.
Now, to your exact problem. The program is telling you it expected command line arguments, but they were not provided. Provide them!
Run this command:
python add.py 1 2
This will execute the script and pass 1 as the first argument, 2 as the second argument.
In your case the general format is
python add.py [n] [m]
Now at that point you might be (you should be) wondering what sys.argv[0] is then, any why your n number doesn't get assigned to sys.argv[1].
sys.argv[0] is the name of the script running.
Further reading on command line arguments:
http://www.pythonforbeginners.com/system/python-sys-argv
Additional.
You could modify your script to be more descriptive:
import sys
if len(sys.argv) < 3: #script name + 2 other arguments required
print("Provide at least two numbers")
else:
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)
sys.argv contains the command line parameters. When you run your script in the Python shell you're most likely not sending any parameters. I would suggest adding a check if there are command line arguments present like this:
import sys
if len(sys.argv) > 2:
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)
Check this out to find out more about Python and sys.argv
Related
So I was doing some python exercise and been stuck on one which teaches parameters, unpacking and variables so the code goes like this
from sys import argv
main.py, first, second, third = argv
print("The script is called:", main.py)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
but the error I get running this directly on compiler is
main.py, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 1)
Now if I run the code with terminal using command python3 main.py first second third as the book says I get the error
Traceback (most recent call last):
File "main.py", line 2, in <module>
main.py, first, second, third = argv
NameError: name 'main' is not defined
help would be appreciate
well, when you do:
main.py, first, second, third = argv
you expect to have always four argouments passed to oour file when started, but the Value Error is telling to you that only one has been passed.
Then the second error is raised because you use main.py to define a variable, but you can't use . in variable names, so simply turn your code in:
main, first, second, third = argv
then it should be adviceble to use some try: ... except: statement to handle errors in that part to avoid the brogram crashing when you pass the wrong number of arguments.
if you have a program that requires command line arguments like in that case you have always to start it with the arguments.
to avoid the first error you have to start the file like you do after in the question ,but will work only if you solve the second error.
import sys
try:
main, first, second, third = sys.argv
except ValueError:
first = input("first: ")
second = input("second: ")
third= input("third: ")
#main is the name of the file ,if you eant you can get it using __file__
in the above way you could avoid any error and if for any reason you start the file without passing any arguments, it will ask you them via shell.
I want to resolve bugs of a complex python application written by someone else. I would like to set up Visual Studio Code [VSC] and its debugger so that I can step through the code.
The python application is meant to be run from a linux terminal using arguments, not as python. For this reason I am not able to set up VSC appropriately, nor to run the application's commands in python. As an example I recreated the application using two files:
File1 myprog:
#!/usr/bin/env python
import sys
def format():
#print(' myprog > format: sys.argv=',sys.argv)
import myprog
myprog.format_doc()
def main():
if len(sys.argv) >= 2:
command = sys.argv[1]
if command == '--version':
print('V1.0')
elif command == 'format':
eval(command+'()')
main()
File2 myprogr.py:
import os, sys
def format_doc():
print(' myprog.py > format_doc: sys.argv=',sys.argv)
print(' more complicated code I want to debug using several arguments')
When I run the application from terminal I see that the arguments are passed to File2 in sys.argv (I think as an effect of eval):
bash>./myprog format hello.txt --someoption
myprog.py > format_doc: sys.argv= ['./myprog', 'format', 'hello.txt']
more complicated code I want to debug using arguments
Can I set up VSC to run the above bash command and step into the python code?
Alternatively, can I run the methods in File2 from python so that I can easily debug it in VSC? As you can see I cannot add arguments using python because the python method accepts no input arguments:
>>> import myprog
>>> myprog.format_doc()
myprog.py > format_doc: sys.argv= ['']
more complicated code I want to debug using several arguments
>>> myprog.format_doc("hello.txt","--someoption","or_maybe_some_option")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: format_doc() takes 0 positional arguments but 1 was given
The error is at script, first, second, third = argv. I would like to understand why I am getting the error and how to fix it.
from sys import argv
script, first, second, third = argv
print("The script is called: ", script)
print("The first variable is: ", first)
print("The second variable is: ", second)
print("The third variable is: ", third)
Run it from the shell like this:
python script.py arg1 arg2 arg3
argv variable contains command line arguments. In your code you expected 4 arguments, but got only 1 (first argument always script name). You could configure arguments in pycharm. Go to Run -> Edit Configurations. Then create a new python configuration. And there you could specify Script parameters field. Or you could run your script from command line as mentioned by dnit13.
You could run it like this: python script.py first, second, third
I think you are running the following command:
python script.py
You are writing a program which is aksing for 4 inputs and you are giving onle one. That's why you are receiving an error. You can use the below command:
python script.py Hello How Are
Simply put, how can I differentiate these two in test.py:
python test.py 1
python test.py '1'
Workaround is OK.
Edit:
This workaround looks cool but too complex: argparse
Let the invoker specify args later, in python code use arg = input('Please enter either an integer or a string')
And other workarounds as presented in the answers of this question.
Thank you all for the replies. Every body +1.
The quotes are consumed by the shell. If you want to get them into python, you'll have to invoke like python test.py 1 "'2'" "'3'" 4
It is common handling of args, performed by shell. " and ' are ignored, since you may use them to pass, for instance, few words as one argument.
This means that you can't differentiate '1' and 1 in Python.
The shell command line doesn't support passing arguments of different types. If you want to have commands with arguments of different types you need to write your own command line or at least your own command parser.
Variant 1:
Usage:python test.py "1 2 '3' '4'"
Implementation:
command = sys.argv[1]
arguments = map(ast.literal_eval, command.split())
print arguments
Variant 2:
Usage:
python test.py
1 2 '3' 4'
5 6 '7' 8'
Implementation:
for line in sys.stdin:
arguments = map(ast.literal_eval, line.split())
print arguments
(Of course, you'd probably want to use raw_input to read the command lines, and readline when it is available, that's merely an example.)
A much better solution would be to actually know what kind of arguments you're expected to get and parse them as such, preferably by using a module like argparse.
Windows-specific:
# test.py
import win32api
print(win32api.GetCommandLine())
Example:
D:\>python3 test.py 3 "4"
C:\Python32\python3.EXE test.py 3 "4"
You can then parse the command line yourself.
As you can see from your experiment, the quotes are gone by the time Python is invoked. You'll have to change how the Python is invoked.
I'm not sure how correct I am, but if you're using only integer command line arguments, you can typecast it to be int.
suppose (in *nix), I run my program as:
./test.py 1
I can in my program say something line
import sys
def main():
a=int(sys.argv[1])
I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print ('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
You may have been directed here because you were asking about an IndexError in your code that uses sys.argv. The problem is not in your code; the problem is that you need to run the program in a way that makes sys.argv contain the right values. Please read the answers to understand how sys.argv works.
If you have read and understood the answers, and are still having problems on Windows, check if Python Script does not take sys.argv in Windows fixes the issue. If you are trying to run the program from inside an IDE, you may need IDE-specific help - please search, but first check if you can run the program successfully from the command line.
I would like to note that previous answers made many assumptions about the user's knowledge. This answer attempts to answer the question at a more tutorial level.
For every invocation of Python, sys.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming convention in which argv and argc represent the command line arguments.
You'll want to learn more about lists and strings as you're familiarizing yourself with Python, but in the meantime, here are a few things to know.
You can simply create a script that prints the arguments as they're represented. It also prints the number of arguments, using the len function on the list.
from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))
The script requires Python 2.6 or later. If you call this script print_args.py, you can invoke it with different arguments to see what happens.
> python print_args.py
['print_args.py'] 1
> python print_args.py foo and bar
['print_args.py', 'foo', 'and', 'bar'] 4
> python print_args.py "foo and bar"
['print_args.py', 'foo and bar'] 2
> python print_args.py "foo and bar" and baz
['print_args.py', 'foo and bar', 'and', 'baz'] 4
As you can see, the command-line arguments include the script name but not the interpreter name. In this sense, Python treats the script as the executable. If you need to know the name of the executable (python in this case), you can use sys.executable.
You can see from the examples that it is possible to receive arguments that do contain spaces if the user invoked the script with arguments encapsulated in quotes, so what you get is the list of arguments as supplied by the user.
Now in your Python code, you can use this list of strings as input to your program. Since lists are indexed by zero-based integers, you can get the individual items using the list[0] syntax. For example, to get the script name:
script_name = sys.argv[0] # this will always work.
Although interesting, you rarely need to know your script name. To get the first argument after the script for a filename, you could do the following:
filename = sys.argv[1]
This is a very common usage, but note that it will fail with an IndexError if no argument was supplied.
Also, Python lets you reference a slice of a list, so to get another list of just the user-supplied arguments (but without the script name), you can do
user_args = sys.argv[1:] # get everything after the script name
Additionally, Python allows you to assign a sequence of items (including lists) to variable names. So if you expect the user to always supply two arguments, you can assign those arguments (as strings) to two variables:
user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2
So, to answer your specific question, sys.argv[1] represents the first command-line argument (as a string) supplied to the script in question. It will not prompt for input, but it will fail with an IndexError if no arguments are supplied on the command-line following the script name.
sys.argv[1] contains the first command line argument passed to your script.
For example, if your script is named hello.py and you issue:
$ python3.1 hello.py foo
or:
$ chmod +x hello.py # make script executable
$ ./hello.py foo
Your script will print:
Hello there foo
sys.argv is a list.
This list is created by your command line, it's a list of your command line arguments.
For example:
in your command line you input something like this,
python3.2 file.py something
sys.argv will become a list ['file.py', 'something']
In this case sys.argv[1] = 'something'
Just adding to Frederic's answer, for example if you call your script as follows:
./myscript.py foo bar
sys.argv[0] would be "./myscript.py"
sys.argv[1] would be "foo" and
sys.argv[2] would be "bar" ... and so forth.
In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".
Adding a few more points to Jason's Answer :
For taking all user provided arguments: user_args = sys.argv[1:]
Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.
The syntax is like this: list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.
Suppose you only want to take all the arguments after 3rd argument, then:
user_args = sys.argv[3:]
Suppose you only want the first two arguments, then:
user_args = sys.argv[0:2] or user_args = sys.argv[:2]
Suppose you want arguments 2 to 4:
user_args = sys.argv[2:4]
Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step):
user_args = sys.argv[-1]
Suppose you want the second last argument:
user_args = sys.argv[-2]
Suppose you want the last two arguments:
user_args = sys.argv[-2:]
Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by :):
user_args = sys.argv[-2:]
Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item:
user_args = sys.argv[:-2]
Suppose you want the arguments in reverse order:
user_args = sys.argv[::-1]
sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.
To pass arguments to your python script
while running a script via command line
> python create_thumbnail.py test1.jpg test2.jpg
here,
script name - create_thumbnail.py,
argument 1 - test1.jpg,
argument 2 - test2.jpg
With in the create_thumbnail.py script i use
sys.argv[1:]
which give me the list of arguments i passed in command line as
['test1.jpg', 'test2.jpg']
sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.
example.py
import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument
Now here in the command prompt when we do this:
python example.py
It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code.
If we run the example.py with passing a argument
python example.py args
It prints:
args
Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:
example argumentpassed
It prints:
argumentpassed
It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.
sys.argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
Just try this:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
Now try this running your filename.py like this:
python filename.py example example1
this will print 3 arguments in a list.
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv[1] is the first argument passed, in this case 'example'.