I am trying pass variable values as arguments to a function which I am calling with in a for loop. Somehow before calling the function when I print the variable values they are showing fine but they are not getting passed into function as I am getting Index out of range :0 which means nothing is passed. Researched with no use...your help is really appreciated.
Code is:
for clx in root.findall('sample'):
CName = clx.find('Name').text
No01 = clx.find('First').text
No02 = clx.find('Second').text
print "Cname provided is" +CName
print "First is" +No01
print "Second is" +No02
createCluster(CName, No01, No02)
createCluster:
def createCluster(CName, No01, No02):
print len(sys.argv)
ClsName=sys.argv[0]
Node01=sys.argv[1]
Node02=sys.argv[2]
Error:
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "createCluster.py", line 8, in createCluster
ClsName=sys.argv[0]
IndexError: index out of range: 0
You are not extracting the arguments passed to your method properly. In Python, you simply just use the arguments that you defined in your method like this:
def createCluster(CName, No01, No02):
print(CName)
print(No01)
print(No02)
createCluster('a', 'b', 'c')
The above will output
a
b
c
For your issue on your usage of sys.argv that you are incorrectly using:
Snippet from the documentation on sys.argv:
The list of command line arguments passed to a Python script.
In example of this would be when calling your code from a shell prompt:
python your_script.py a b c
Inside your_script.py you will ahve
import sys
script_name = sys.argve[0]
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
Which will output:
/absolute/path/to/your_script.py
a
b
c
So, you see here that it ends up giving you the name of the script and all arguments.
This is maybe where your confusion came from between calling a script and calling the method in the script.
Related
I'm using cmd.exe on windows7 to execute a python script via this line :
> csv_cleaner.py ../test.csv ../oui.csv
The first lines of the script are :
import configparser, csv, sys
if len(sys.argv) < 3 :
usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \
arguments to function properly.\n[input file] is the file to clean\n[output fil\
e] is the name of the file that will be created as a result of this
program\n"""
print(usage % (sys.argv[0]))
else :
The problem is that no matter how many arguments I pass the check always fail, furthermore when I try printing any argument beyond the first I receive this error.
These lines were added for debug but are not in the actual program
File "C:\Users\comte\Desktop\csv_cleaner\csv_cleaner.py", line 3, in <module>
print(sys.argv[2])
IndexError: list index out of range
len(sys.argv) returns 1
If you try to access a non-existing item of the sys.argv list, Python throws a IndexError exception.
Instead, if you want to check how much parameters have been passed to the cammand-line, you can use len(sys.argv):
if len(sys.argv) <= 2 :
usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \
arguments to function properly.\n[input file] is the file to clean\n[output fil\
e] is the name of the file that will be created as a result of this
program\n"""
print(usage % (sys.argv[0]))
The problem was seemingly an artifact from an uninstalled python2 in my PATH.
Now that it is removed everything works fine.
I am trying to execute below python script. But getting below issue after execution.
Code
#!/usr/bin/python
def Student(Student_Id):
msg = Student_Id + "." +
return msg
Error
C:\Users\Desktop>Test.py 2asd
After an investigation found that argument which I am passing through the command line is considered as Null.
You need to call like
Test.py -n 2asd
I have a added .PY files to my System Environment PATHEXT variable on Windows 7. I have also added C:\scripts to my PATH variable.
Consider I have a very simple Python file C:\Scripts\helloscript.py
print "hello"
Now I can call Python scripts from my Console using:
C:\>helloscript
And the output is:
hello
If I change the script to be more dynamic, say take a first name as a second parameter on the Console and print it out along with the salutation:
import sys
print "hello,", sys.argv[1]
The output is:
c:\>helloscript brian
Traceback (most recent call last):
File "C:\Scripts\helloscript.py", line 2, in <module>
print sys.argv[1]
IndexError: list index out of range
sys.argv looks like:
['C:\\Scripts\\helloscript.py']
If I call the script explicitly the way I would normally:
C:\>python C:\Scripts\helloscript.py brian
The output is:
hello, brian
If I try to use optparse the result is similar although I can avoid getting an error:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--firstname", action="store", type="string", dest="firstname")
(options, args) = parser.parse_args()
print "hello,", options.firstname
The output is:
hello, None
Again, the script works fine if I call it explicitly.
Here's the question. What's going on? Why doesn't sys.argv get populated with more than just the script name when calling my script implicitly?
It turns out I had to manually edit the registry:
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command was:
"C:\Python27\python.exe" "%1"
And should have been:
"C:\Python27\python.exe" "%1" %*
Hey guys I was trying to use the argument variable in Python however am unable to execute the program at the terminal.
Program:
from sys import argv
script,first,second,third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Output:
>>> execfile("lesson13.py","dog","cat")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be dict, not str
>>>
execfile() doesn't take command arguments. Try using subprocess instead.
How do you accept/parse command line arguments for a py file that has no class? Here is what I have inside my file test.py:
import sys
if __name__ == '__main__':
How do I get the arguments when the file is executed via command line? I call it via:
python test.py <arg1>
and obviously want the value of "arg1".
Look no further than sys.argv, which is a list containing all arguments passed to the program.
try:
arg = sys.argv[1]
except IndexError:
print "No argument specified."
sys.exit(1)