Command line argument with python - 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

Related

Command line from cmd not parsed correctly

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.

Python's sh module - is it at all possible for a script to request input?

Using Python's sh, I am running 3rd party shell script that requests my input (not that it matters much, but to be precise, I'm running an Ansible2 playbook with the --step option)
As an oversimplification of what is happening, I built a simple bash script that requests an input. I believe that if make this simple example work I can make the original case work too.
So please consider this bash script hello.sh:
#!/bin/bash
echo "Please input your name and press Enter:"
read name
echo "Hello $name"
I can run it from python using sh module, but it fails to receive my input...
import errno
import sh
cmd = sh.Command('./hello.sh')
for line in cmd(_iter=True, _iter_noblock=True):
if line == errno.EWOULDBLOCK:
pass
else:
print(line)
How could I make this work?
After following this tutorial, this works for my use case:
#!/usr/bin/env python3
import errno
import sh
import sys
def sh_interact(char, stdin):
global aggregated
sys.stdout.write(char)
sys.stdout.flush()
aggregated += char
if aggregated.endswith(":"):
val = input()
stdin.put(val + "\n")
cmd = sh.Command('./hello.sh')
aggregated = ""
cmd(_out=sh_interact, _out_bufsize=0)
For example, the output is:
$ ./testinput.py
Please input your name and press Enter:arod
Hello arod
There are two ways to solve this:
Using _in:
using _in, we can pass a list which can be taken as input in the python script
cmd = sh.Command('./read.sh')
stdin = ['hello']
for line in cmd(_iter=True, _iter_noblock=True, _in=stdin):
if line == errno.EWOULDBLOCK:
pass
else:
print(line)
Using command line args if you are willing to modify the script.

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.

pass variable in to command in python

i'm writing a python script to execute shell command, and i'm taking arguments and i want to pass the value of that to the command
#!/usr/bin/env python
import commands
import subprocess
import sys
command = commands.getoutput('fs_cli -x "sofia profile external restart"')
this code works fine
when i try to take the argument and pass to command it fails
command = commands.getoutput('fs_cli -x "sofia profile" + sys.argv[1]
+ " restart"')
supp folks
You should write:
command = commands.getoutput('fs_cli -x "sofia profile ' + sys.argv[1] + ' restart"')
Take a look to argparse and subprocess.
One of the way to do this is to convert your command that you want to execute into string and then execute it as eval()
example :
eval(expression/command in string)

Python: -bash: syntax error near unexpected token

I have written a little script in Python that I use to append text to a work log. I have placed the script in a directory in my $PATH
#!/usr/bin/python
# import necessary modules
import sys
import os
import datetime
# main() function
def main():
now = datetime.datetime.now()
tmp = ' '.join(sys.argv[1:])
outfile = '/path/to/output/done.log'
outstr = now.strftime("%Y-%m-%d %H:%M:%S") + ' - ' + tmp + '\n'
f=open(outfile,'a')
f.write(outstr)
f.close()
# print sys.argv[0:1]
print 'Adding ' + outstr
# Call main()
if __name__ == '__main__':
main()
When I run the script as in example 1, I get an error.
Example 1:
host:scripts user$ done this is a test
-bash: syntax error near unexpected token `done'
If I run the script as in example 2, it behaves as expected.
Example 2:
host:scripts user$ python done this is a test
Adding 2012-11-15 09:57:44 - this is a test
How do I get this to work in the first example?
done is a bash keyword, so can't be used in certain places like "the place Bash expects a command name". You could use ./done (or /path/to/done, or python /path/to/done), or re-name the command.

Categories