Command line from cmd not parsed correctly - python

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.

Related

Command line argument with python

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

pass variable values as arguments to a python function

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.

How to handle python raw_input() in batch file

I created a batch file to run files in sequence, however my python file takes in an input (from calling raw_input), and I am trying to figure out how to handle this over the batch file.
run.bat
The program doesn't proceed to the next line after the .py file is executed, for brevity i just just showed necessary commands
cd C:\Users\myname\Desktop
python myfile.py
stop
myfile.py
print ("Enter environment (dev | qa | prod) or stop to STOP")
environment = raw_input()
Here's a solution.
Take your myfile.py file, and change it to the following:
import sys
def main(arg = None):
# Put all of your original myfile.py code here
# You could also use raw_input for a fallback, if no arg is provided:
if arg is None:
arg = raw_input()
# Keep going with the rest of your script
# if __name__ == "__main__" ensures this code doesn't run on import statements
if __name__ == "__main__":
#arg = sys.argv[1] allows you to run this myfile.py directly 1 time, with the first command line paramater, if you want
if len(sys.argv) > 0:
arg = sys.argv[1]
else:
arg = None
main(arg)
Then create another python file, called wrapper.py:
#importing myfile here allows you to use it has its own self contained module
import sys, myfile
# this loop loops through the command line params starting at index 1 (index 0 is the name of the script itself)
for arg in sys.argv[1 : ]:
myfile.main(arg)
And then at the command line, you can simply type:
python wrapper.py dev qa prod
You could also put the above line of code in your run.bat file, making it look at follows:
cd C:\Users\myname\Desktop
python wrapper.py dev qa prod
stop
the question is not related to python. To your shell. According http://ss64.com/nt/syntax-redirection.html cmd.exe uses the same syntax as unix shell (cmd1 | cmd2), so your bat file should work fine when called with command, which will send the file content to standard output.
Edit: added example
echo "dev" | run.bat
C:\Python27\python.exe myfile.py
Enter environment (dev | qa | prod) or stop to STOP
environment="dev"

Quoted string as optional argument to Python script

I have simple utility script that I use to download files given a URL. It's basically just a wrapper around the Linux binary "aria2c".
Here is the script named getFile:
#!/usr/bin/python
#
# SCRIPT NAME: getFile
# PURPOSE: Download a file using up to 20 concurrent connections.
#
import os
import sys
import re
import subprocess
try:
fileToGet = sys.argv[1]
if os.path.exists(fileToGet) and not os.path.exists(fileToGet+'.aria2'):
print 'Skipping already-retrieved file: ' + fileToGet
else:
print 'Downloading file: ' + fileToGet
subprocess.Popen(["aria2c-1.8.0", "-s", "20", str(fileToGet), "--check-certificate=false"]).wait() # SSL
except IndexError:
print 'You must enter a URI.'
So, for example, this command would download a file:
$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg
What I want to do is permit an optional second argument (after the URI) that is a quoted string. This string will be the new filename of the downloaded file. So, after the download finishes, the file is renamed according to the second argument. Using the example above, I would like to be able to enter:
$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg "van-Gogh-painting.jpg"
But I don't know how to take a quoted string as an optional argument. How can I do this?
Just test the length of sys.argv; if it is more than 2 you have an extra argument:
if len(sys.argv) > 2:
filename = sys.argv[2]
The shell will pass it as a second argument (normally) if you provide spaces between them.
For example, here is test.py:
import sys
for i in sys.argv:
print(i)
And here is the result:
$ python test.py url "folder_name"
test.py
url
folder_name
The quotes doesn't matter at all, as it's handled in the shell, not python. To get it, just take sys.argv[2].
Hope this helps!

Python, command line argument parsing

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)

Categories