something about “from sys import argv” [duplicate] - python

I am trying to debug a script which takes command line arguments as an input. Arguments are text files in the same directory. Script gets file names from sys.argv list. My problem is I cannot launch the script with arguments in pycharm.
I have tried to enter arguments into "Script parameters" field in "Run" > "Edit configuration" menu like so:
-s'file1.txt', -s'file2.txt'
But it did not work. How do I launch my script with arguments?
P.S. I am on Ubuntu

In PyCharm the parameters are added in the Script Parameters as you did but, they are enclosed in double quotes "" and without specifying the Interpreter flags like -s. Those flags are specified in the Interpreter options box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0] holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']

For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations (to the left of ) and going to the Edit Configurations. A
gif provided for clarity.

On PyCharm Community or Professional Edition 2019.1+ :
From the menu bar click Run -> Edit Configurations
Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
Click Apply
Click OK

In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:
python mediadb.py /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png
the PyCharm parameter would be:
"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"

Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.

Add the following to the top of your Python file.
import sys
sys.argv = [
__file__,
'arg1',
'arg2'
]
Now, you can simply right click on the Python script.

The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
And here is how you pass the input parameters :
'Path to your script','First Parameter','Second Parameter'
Lets say that the Path to your script is /home/my_folder/test.py, the output will be like :
Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter
It took me some time to figure out that input parameters are comma separated.

I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".

It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.

In edit configuration of PyCharm when you are giving your arguments as string, you should not use '' (these quotations) for giving your input.
Instead of -s'file1.txt', -s'file2.txt'
simply use:
-s file1.txt, -s file2.txt

you can used -argName"argValue" like -d"rd-demo" to add Pycharm arguments
-d"rd-demo" -u"estate"
Arguments added in Parameters Section after selected edit Configuration from IDE

I'm using argparse, and in order to debug my scripts I also using Edit Configuration. For example below the scripts gets 3 parameters (Path, Set1, N) and an optional parameter (flag):
'Path' and 'Set1' from type str.
'N' from type int.
The optional parameter 'flag' from type boolean.
impor argparse
parser = argparse.ArgumentParser(prog='main.py')
parser.add_argument("Path", metavar="path", type=str)
parser.add_argument("Set1", type=str, help="The dataset's name.")
parser.add_argument("N", type=int, help="Number of images.")
parser.add_argument("--flag", action='store_true')
params = parser.parse_args()
In order to to run this in a debug or not by using command line, all needed is:
bar menu Run-->Edit Configuration
Define the Name for your debug/run script.
Set the parameters section. For the above example enter as follow:
The defualt 3 parameters must me included --> "c:\mypath" "name" 50
For the optional parameter --> "c:\mypath" "name" 50 "--flag"
parameter section

Related

Python: builtins.IndexError: list index out of range [duplicate]

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'.

In Python, how to supply the command line arguments in interactive mode

I am new to Python. I want to run a software in interactive mode. In the manual it says the usage
python experiment.py --config config.yaml --out result/
The question is, how can I supply the command line arguments to experiment.py in interactive mode?
The commandline arguments that e.g. optparse and argparse uses are taken by default from sys.argv element 1 and up. You can always do:
import sys
sys.argv[1:] = ['--config', 'config.yaml', '--out', 'result/']
Although e.g. in argparse you can provide the arguments explicitly to .parse_args() as well and then that method will not inspect sys.argv
If I understood you correctly you need something like this:
while True:
query = raw_input("> ")
if query == "exit":
break
# do something useful

Pycharm and sys.argv arguments

I am trying to debug a script which takes command line arguments as an input. Arguments are text files in the same directory. Script gets file names from sys.argv list. My problem is I cannot launch the script with arguments in pycharm.
I have tried to enter arguments into "Script parameters" field in "Run" > "Edit configuration" menu like so:
-s'file1.txt', -s'file2.txt'
But it did not work. How do I launch my script with arguments?
P.S. I am on Ubuntu
In PyCharm the parameters are added in the Script Parameters as you did but, they are enclosed in double quotes "" and without specifying the Interpreter flags like -s. Those flags are specified in the Interpreter options box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0] holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations (to the left of ) and going to the Edit Configurations. A
gif provided for clarity.
On PyCharm Community or Professional Edition 2019.1+ :
From the menu bar click Run -> Edit Configurations
Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
Click Apply
Click OK
In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:
python mediadb.py /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png
the PyCharm parameter would be:
"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"
Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.
Add the following to the top of your Python file.
import sys
sys.argv = [
__file__,
'arg1',
'arg2'
]
Now, you can simply right click on the Python script.
The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
And here is how you pass the input parameters :
'Path to your script','First Parameter','Second Parameter'
Lets say that the Path to your script is /home/my_folder/test.py, the output will be like :
Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter
It took me some time to figure out that input parameters are comma separated.
I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".
It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.
In edit configuration of PyCharm when you are giving your arguments as string, you should not use '' (these quotations) for giving your input.
Instead of -s'file1.txt', -s'file2.txt'
simply use:
-s file1.txt, -s file2.txt
you can used -argName"argValue" like -d"rd-demo" to add Pycharm arguments
-d"rd-demo" -u"estate"
Arguments added in Parameters Section after selected edit Configuration from IDE
I'm using argparse, and in order to debug my scripts I also using Edit Configuration. For example below the scripts gets 3 parameters (Path, Set1, N) and an optional parameter (flag):
'Path' and 'Set1' from type str.
'N' from type int.
The optional parameter 'flag' from type boolean.
impor argparse
parser = argparse.ArgumentParser(prog='main.py')
parser.add_argument("Path", metavar="path", type=str)
parser.add_argument("Set1", type=str, help="The dataset's name.")
parser.add_argument("N", type=int, help="Number of images.")
parser.add_argument("--flag", action='store_true')
params = parser.parse_args()
In order to to run this in a debug or not by using command line, all needed is:
bar menu Run-->Edit Configuration
Define the Name for your debug/run script.
Set the parameters section. For the above example enter as follow:
The defualt 3 parameters must me included --> "c:\mypath" "name" 50
For the optional parameter --> "c:\mypath" "name" 50 "--flag"
parameter section

Python script argument conditional

Is anyone able to tell me how to write a conditional for an argument on a python script? I want it to print "Argument2 Entered" if it is run with a second command line arguments such as:
python script.py argument1 argument2
And print "No second argument" if it is run without command line arguments, like this:
python script.py argument1
Is this possible?
import sys
if len(sys.argv)==2: # first entry in sys.argv is script itself...
print "No second argument"
elif len(sys.argv)==3:
print "Second argument"
There are many answers to this, depending on what exactly you want to do and how much flexibility you are likely to need.
The simplest solution is to examine the variable sys.argv, which is a list containing all of the command-line arguments. (It also contains the name of the script as the first element.) To do this, simply look at len(sys.argv) and change behaviour based on its value.
However, this is often not flexible enough for what people expect command-line programs to do. For example, if you want a flag (-i, --no-defaults, ...) then it's not obvious how to write one with just sys.argv. Likewise for arguments (--dest-dir="downloads"). There are therefore many modules people have written to simplify this sort of argument parsing.
The built-in solution is argparse, which is powerful and pretty easy-to-use but not particularly concise.
A clever solution is plac, which inspects the signature of the main function to try to deduce what the command-line arguments should be.
There are many ways to do this simple thing in Python. If you are interested to know more than I recommend to read this article. BTW I am giving you one solution below:
import click
'''
Prerequisite: # python -m pip install click
run: python main.py ttt yyy
'''
#click.command(context_settings=dict(ignore_unknown_options=True))
#click.argument("argument1")
#click.argument("argument2")
def main(argument1, argument2):
print(f"argument1={argument1} and argument2={argument2}")
if __name__ == '__main__':
main()
Following block should be self explanatory
$ ./first.py second third 4th 5th
5
$ cat first.py
#!/usr/bin/env python
import sys
print (len(sys.argv))
This is related to many other posts depending upon where you are going with this, so I'll put four here:
What's the best way to grab/parse command line arguments passed to a Python script?
Implementing a "[command] [action] [parameter]" style command-line interfaces?
How can I process command line arguments in Python?
How do I format positional argument help using Python's optparse?
But the direct answer to your question from the Python docs:
sys.argv -
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.

Passing command Line argument to Python script within Eclipse(Pydev)

I am new to Python & Eclipse, and having some difficulties understanding how to pass command line argument to script running within Eclipse(Pydev).
The following link explains how to pass command line argument to python script.
To pass command line argument to module argecho.py(code from link above),
#argecho.py
import sys
for arg in sys.argv: 1
print arg
I would need to type into python console
[you#localhost py]$ python argecho.py
argecho.py
or
[you#localhost py]$ python argecho.py abc def
argecho.py
abc
def
How would I pass same arguments to Python script within Eclipse(Pydev) ???
Thanks !
Click on the play button down arrow in the tool bar -> run configurations -> (double click) Python Run -> Arguments tab on the right hand side.
From there you can fill out the Program Arguments text box:
If you want your program to ask for arguments interactively, then they cease to be commandline arguments, as such. However you could do it something like this (for debugging only!), which will allow you to interactively enter values that the program will see as command line arguments.
import sys
sys.argv = raw_input('Enter command line arguments: ').split()
#Rest of the program here
Note that Andrew's way of doing things is much better. Also, if you are using python 3.*, it should be input instead of raw_input,
Select "Properties" -->> "Run/Debug Settings".
Select the related file in right panel and then click on "Edit" button. It will open properties of selected file. There's an "Arguments" tab.
Years later, and not Eclipse,
but a variant of other answers to run my.py M=11 N=None ... in sh or IPython:
import sys
# parameters --
M = 10
N = 20
...
# to change these params in sh or ipython, run this.py M=11 N=None ...
for arg in sys.argv[1:]:
exec( arg )
...
myfunc( M, N ... )
See One-line-arg-parse-for-flexible-testing-in-python
under gist.github.com/denis-bz .
What I do is:
Open the project in debug perspective.
In the console, whenever the debugger breaks at breakpoint, you can type python command in the "console" and hit return (or enter).
There is no ">>" symbol, so it is hard to discover.
But I wonder why eclipse doesn't have a python shell :(

Categories