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)
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 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.
I need to use sys.argv to check for an argument from the command line, which would be the filename in my case. My code is as follows. I'm not allowed to import argparse, only allowed to use sys. I know I'm doing something wrong here. Appreciate any help.
def get_inputfile_object( ):
'''
Check the command line for an argument. If one was there, use it as the
filename. Otherwise, use DEFAULT_INPUT_FILENAME. Open the file.
If file is successfully opened:
print MSG_OPENING_FILE
Return: a file object for that file
If the file cannot be opened:
print MSG_ERROR_OPENNING_FILE
Return: True
'''
if sys.argv > 1:
pass
else:
input_filename = DEFAULT_INPUT_FILENAME
input_filename = DEFAULT_INPUT_FILENAME
if os.path.isfile(input_filename) and os.access(input_filename,os.R_OK):
#Prints the opening file message, and the name of the file
print (MSG_OPENING_FILE,input_filename)
return open(input_filename,'r')
else:
print (MSG_ERROR_OPENING_FILE)
return True
sys.argv is a list of arguments.
You need to check the length of the list:
if len(sys.argv) > 1:
You should check out argparse.
The argparse module also automatically generates help and usage
messages and issues errors when users give the program invalid
arguments.
Haven't tested it, but you can try something similar to this:
import argparse
# setup the parser
parser = argparse.ArgumentParser(description='Describe script')
# add positional argument
parser.add_argument('filename', type=str, help='filename description')
# parse the args
args = parser.parse_args()
print(args.filename)
I'm trying to parse the command line arguments in a very simple way:
$ python main.py --path /home/me/123
or
$ python main.py --path=/home/me/123
And then:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path')
args = parser.parse_args()
And args returns nothings:
(Pdb) args
(Pdb) args.path
How can I access the value of --path?
You can print args.path and it will show your line argument. For more details you can check the below link for more details about argparse
Argparse Tutorial
You can also use sys to parse your command line arguments, such as
>>> import sys
>>> path = sys.argv[1] # sys.argv always start at 1
>>> print path
Check the below link for more details.
Python Command Line Arguments
Hope it helps.
It works fine for me...
>>> args
Namespace(path='/home/me/123')
So you can access it via args.path
I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. Any ideas? I imagine its something simple that I am overlooking. Any and all help is great, thanks, Justin.
[justin87#el-beasto-loco python]$ python openall.py -f chords.tar
Usage: openall.py [options] arg
openall.py: error: incorrect number of arguments
[justin87#el-beasto-loco python]$
#!/usr/bin/python
import tarfile
import os
import zipfile
from optparse import OptionParser
def check_tar(file):
if tarfile.is_tarfile(file):
return True
def open_tar(file):
try:
tar = tarfile.open(file)
tar.extractall()
tar.close()
except tarfile.ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except tarfile.CompressionError:
print "Compression method is not supported or data cannot be decoded"
except tarfile.StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except tarfile.ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
def check_zip(file):
if zipfile.is_zipfile(file):
return True
def open_zip(file):
try:
zip = zipfile.ZipFile(file)
zip.extractall()
zip.close()
#open the zip
print "GOT TO OPENING"
except zipfile.BadZipfile:
print "The error raised for bad ZIP files (old name: zipfile.error)."
except zipfile.LargeZipFile:
print "The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled."
rules = ((check_tar, open_tar),
(check_zip, open_zip)
)
def checkall(file):
for checks, extracts in rules:
if checks(file):
return extracts(file)
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = options.filename
checkall(file)
if __name__ == '__main__':
main()
Your problem is probably the if len(args) != 1:. That is looking for an additional argument (i.e. not an option). If you remove that check and look at your options dictionary you should see {'filename': 'blah'}.
Your input filename isn't an option to the program, it's an argument:
def main():
usage = "Usage: %prog [options] FILE"
description = "Read data from FILE."
parser = OptionParser(usage, description=description)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
file = args[0]
checkall(file)
You can usually tell the difference because options generally have sensible defaults while arguments don't.
After parsing the options out of the argument list, you check that you were passed an argument. This is independent of the argument to -f. It sounds like you're just not passing this argument. Since you also don't actually use this argument, you should probably just remove the check on len(args).
You should set the 'action' attribute in the 'add_option()' method to 'store', this tells the optparse object to store the argument immediately following the option flag, though this is the default behavior. The value following the flag will then be stored in 'options.filename' and not in args. I also think that the
if len(args) != 1:
is also an issue, you will get the same message if len(args) is greater than or less than 1.