Variables not saved using getopt for command line options (python) - python

I am trying to create a program in python and my biggest problem is getting it to use command line options to assign the variables in the program. I have been using getopt and it will print from where I define it, but the variables can not be called upon outside of the definition so that I can use for the rest of my program.
In the code below, the print state for the "Is the following correct" comes out fine but if I try to print the gender or any other variable after the code, I just get an error that it isn't defined.
By the way, the options I run are: spice.py -g m -n 012.345.6789 -r 23 -e 13 -o voicemail.mp3
Code:
import sys
import getopt
def main(argv):
gender = 'missing'
phone = 'missing'
reasons = 'missing'
endings = 'missing'
output = 'missing'
try:
opts, args = getopt.getopt(argv, "hg:n:r:e:o:")
except getopt.GetoptError:
print 'spice.py -g <gender> -n <phone number> -r <reasons> -e <endings> -o <output name>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-g"):
gender = arg
elif opt in ("-n"):
phone = arg
elif opt in ("-r"):
reasons = arg
elif opt in ("-e"):
endings = arg
elif opt in ("-o"):
output = arg
print "Is the following correct? " + "Gender: " + gender + ", " + "Phone Number: " + phone + ", " + "Reasons: " + reasons + ", " + "Endings: " + endings + ", " + "Output: " + output
if __name__ == "__main__":
main(sys.argv[1:])
print gender

in your code, gender is not global. it's only in context within the function.
as proof, change the first couple of lines to:
import sys
import getopt
gender = 'missing'
def main(argv):
global gender
# ... all the same
# ... below here
and you'll now see that it prints (assuming it was working in context as you describe).
when you refactor you'll actually want to either write functions that return the values you want to use and then use them or create global variables and clean up the code a bit.

Related

Choose multiple optional arguments with argparse in Python 3

I am using argparse in Python 3 to accept command-line arguments into a script.
import argparse
cli_argparser = argparse.ArgumentParser(description='')
cli_argparser.add_argument('-n', '--number', type=int, help="Pass a number 'n' to script.", required=False)
cli_argparser.add_argument('-q', '--query', help="Pass a query to the script", required=False)
cli_argparser.add_argument('-o', '--outfile', help="Saves the output to an external file.", required=False)
cli_args = cli_argparser.parse_args()
if (cli_args.number):
print ("\n--number has the value '" + str(cli_args.number) + "'\n")
elif (cli_args.query):
print ("\n--query has the value '" + cli_args.query + "'\n")
elif (cli_args.outfile):
print ("\n--output has the value '" + cli_args.outfile + "'\n")
else:
print ("\nNo Arguments passed. Set or Use a default value...\n")
Is there a way to make sure that if one specific argument is selected, another one MUST be specified? For instance, if -o is specified, it must also contain -n before or after -o.
I tried adding an if condition, like so:
if (cli_args.number):
print ("\n--number has the value '" + str(cli_args.number) + "'\n")
elif (cli_args.query):
print ("\n--query has the value '" + cli_args.query + "'\n")
elif (cli_args.outfile):
if (cli_args.number):
print ("\n--output has the value '" + cli_args.outfile + "'\n")
else:
print ("\n--number not specified. Exit..")
else:
print ("\nNo Arguments passed. Set or Use a default value...\n")
The result is that, if only -o is specified, the script exits (as expected), however, if -n is added, the first condition is True.
$ python test.py -o output.txt
--number not specified. Exit..
$ python test.py -o output.txt -n 100
--number has the value '100'
How would I modify this such that if only -n is specified, the 1st condition is true and if -o is specified, it requires -n too and then executes the 3rd condition? Would something like cli_args.number AND cli_args.outfile work? Or is there an in-built function in argparse for this?
elif (cli_args.outfile):
if (cli_args.number):
print ("\n--output has the value '" + cli_args.outfile + "'\n")
This branch of logic is unreachable in your code as whenever cli_args.number is true, it would have fulfilled the first condition in your if ... else branch.
You could check for outfile and number first, or you could change the logic in the first if statement to if number and not outfile.

Executing python functions with multiple arguments in terminal

I have written a python function which takes multiple arguments and i want it to run from terminal but it's not working. what am I doing wrong?
counting.py script:
def count (a, b):
word = False
a = " " + a + " "
b = " " + b + " "
result = 0
for i in range (len (a)-1):
if a[i] == " " and a[i+1] != " ":
word = True
result += 1
else:
word = False
for i in range (len (b)-1):
if b[i] == " " and b[i+1] != " ":
word = True
result += 1
else:
word = False
return result
if __name__ == "__main__":
count (a, b)
terminal command:
python counting.py count "hello world" "let's check you out"
useing sys model,
add this code, the sys.argv first parameter is this file name
import sys
if __name__ == "__main__":
a = sys.argv[1]
b = sys.argv[2]
count(a,b)
terminal command:
python counting.py "hello word" "let's check you out"
ex:
import sys
def count(s1, s2):
print s1 + s2
print sys.argv
count(sys.argv[1], sys.argv[2])
out:
python zzzzzzz.py "hello" "word"
['zzzzzzz.py', 'hello', 'word']
helloword
a and b are the arguments of count. You cannot use them outside that scope. You could instead use sys.argv to access the commandline arguments:
from sys import argv
if __name__ == "__main__":
print(count (argv[1], argv[2]))
As suggested by others using sys:
from sys import argv
def count(a, b):
return len(a.split(" ")) + len(b.split(" "))
if __name__ == "__main__":
a = argv[1]
b = argv[2]
word_count = count(a, b)
print(word_count)
Or, you could use the built-in module argparse. In case you ever have a more complex script taking arguments from the console.
import argparse
def count(a, b):
return len(a.split(" ")) + len(b.split(" "))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Word Count")
parser.add_argument("-a", type=str, help="First Sentence")
parser.add_argument("-b", type=str, help="Second Sentence")
args = parser.parse_args()
word_count = count(args.a, args.b)
print(word_count)
Execute your script with python counting.py -a "hello world" -b "let's check you out".
And if you execute python counting.py -h, you'll get a nicely formatted help for the users:
usage: counting.py [-h] [-a A] [-b B]
Word Count
optional arguments:
-h, --help show this help message and exit
-a A First Sentence
-b B Second Sentence

Python commandline parameter not raising error if argument is wrongly used

I have the following Python code that has 1 command line optional parameter (c) that has an argument and 2 options (a and b) that do not have an argument:
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"abc:",["csvfile="])
except getopt.GetoptError:
print 'Error in usage - a does not require an argument'
sys.exit(2)
for opt, arg in opts:
print "Raw input is: {}" .format(opt)
if opt in ("-c", "--csvfile"):
outputfile = arg
print 'Output file is {}' .format(outputfile)
elif opt == '-a':
print 'Alpha'
elif opt == '-b':
print 'Beta'
print 'User choice is {}' .format(opt.lstrip('-'))
if __name__ == "__main__":
main(sys.argv[1:])
When I enter python readwritestore.py -a I get:
Raw input is: -a
Alpha
User choice is a
This is what I was hoping for if the commandline argument is -a. However, if I enter python readwritestore.py -a csvfile_name, then I get:
Raw input is: -a
Alpha
User choice is a
This is not what I intended for. In this function, c is the only option that rquires an argument. If I enter a with an argument,
the code should give the error message that I set up
Error in usage - a does not require an argument
This does not happen for a or b. It is allowing the argument to be entered without raising an error.
If the options that do not require an argument are entered with an argument, then I would like it to raise an error. python readwritestore.py -a text
and python readwritestore.py -b text should raise the error Error in usage - a does not require an argument.
Is there a way to specify this? Is getopt() the correct way to do this?
Additional Information:
I only want python readwritestore.py -c text to work with the argument. For the other 2 options, a and b, the code should raise the error.
checking the size of sys.argv (the list of argument supplied when calling the script) can help you checking that :
import sys
import getopt
def main(argv):
inputfile = ''
outputfile = ''
opts, args = getopt.getopt(argv, "abc:", ["csvfile="])
for opt, arg in opts:
print "Raw input is:", opt
if opt in ("-c", "--csvfile"):
outputfile = arg
print 'Output file is ', outputfile
elif opt == '-a':
if len(sys.argv)=2:
print 'Alpha'
else:
print "incorect number of argument"
elif opt == '-b':
if len(sys.argv)=2:
print 'Beta'
else:
print "incorect number of argument"
print 'User choice is ', opt
if __name__ == "__main__":
main(sys.argv[1:])
I know it's not what you asked (argparse) but here is how you could do it with argparse :
from argparse import *
def main():
parser = ArgumentParser()
parser.add_argument('-c', '--csvfile', help='do smth with cvsfile')
parser.add_argument(
'-a', '--Alpha', help='Alpha', action='store_true')
parser.add_argument(
'-b', '--Beta', help='beta smth', action='store_true')
if args.csvfile:
print 'Output file is {}' .format(args.csvfile)
if args.Alpha:
print 'Alpha'
if args.Beta:
print 'Beta'
if __name__ == "__main__":
main()
It will raise an error is to many argument are supplied. (also python readwritestore.py -h will display the help just like man in unix)

Making two functions print their output on the same line

I'm making an interpreter, and I have a function called parse(). The parse function returns some output.
I'm making a command that prints two command's outputs on the same line instead of on separate lines.
I have the following code:
def print_command2(command):
command = command.split("_") # The underscore separates the two commands
command[0] = command[0].strip("! ") # The command is !
print(parse(command[0])), # This should print the output of the first command
print(parse(command[1])) # And this should print the second
I typed in the following command to test it:
! p Hello_p World
(p is the equivalent of Python's print command.)
But it outputs the following:
Hello
World
I want it to print this:
HelloWorld
What's wrong?
EDIT: The answer from this question prints the following:
Hello
World
So it doesn't work as wanted.
EDIT: Here's the parse function. Please don't mind the terrible code.
def parse(command):
"""Parses the commands."""
if ';' in command:
commands = command.split(";")
for i in commands:
parse(i)
if '\n' in command:
commands = command.split('\n')
for i in commands:
parse(i)
elif command.startswith("q"):
quine(command)
elif command.startswith("p "):
print_command(command)
elif command.startswith("! "):
print_command2(command)
elif command.startswith("l "):
try:
loopAmount = re.sub("\D", "", command)
lst = command.split(loopAmount)
strCommand = lst[1]
strCommand = strCommand[1:]
loop(strCommand, loopAmount)
except IndexError as error:
print("Error: Can't put numbers in loop")
elif '+' in command:
print (add(command))
elif '-' in command:
print (subtract(command))
elif '*' in command:
print (multiply(command))
elif '/' in command:
print (divide(command))
elif '%' in command:
print (modulus(command))
elif '=' in command:
lst = command.split('=')
lst[0].replace(" ", "")
lst[1].replace(" ", "")
stackNum = ''.join(lst[1])
putOnStack(stackNum, lst[0])
elif command.startswith("run "):
command = command.replace(" ", "")
command = command.split("run")
run(command[1])
elif command.startswith('#'):
pass
elif command.startswith('? '):
stackNum = command[2]
text = input("input> ")
putOnStack(text, stackNum)
elif command.startswith('# '):
stackNum = command[2]
print(''.join(stack[int(stackNum)]))
elif command.startswith("."):
time.sleep(2)
else:
print("Invalid command")
return("")
TL;DR: I'm calling two functions. I want their output to print on the same line.
the print() function has extra arguments you can pass to it. You are interested in end.
def test1():
print('hello ', end='')
def test2():
print('there', end='')
test1()
test2()
>>>
hello there
>>>
It doesn't matter how many functions this comes from

command line arguments not being recognised

Im trying to send some command line arguments to a program I've written. I adapted some code I found in a tutorial. However, only the last of the arguments I am sending seam to be getting through. For example, if I type the following in:
python test.py -m A
Nothing happens, however, if I type in:
python test.py -s A
the final argument in the list it seams to work... (code attached below)
import sys, getopt
def main(argv):
mina = ""
capsize= ""
matchcharge= ""
steps= ""
try:
opts, args = getopt.getopt(argv,"m:cs:mc:s:",["min=","capsize=","matchcharge=","steps="])
except getopt.GetoptError:
print("argument not recognised")
sys.exit(2)
for opt, arg in opts:
if opt == ("-m", "--min"):
mina = arg
print("1")
elif opt in ("-cs", "--capsize"):
capsize = arg
print("2")
elif opt in ("-mc", "--matchcharge"):
matchcharge = arg
print("3")
elif opt in ("-s", "--steps"):
steps = arg
print("4")
print("mina " + str(min))
print("capsize" + str(capsize))
print("matchcharge" + str(matchcharge))
print("steps " + str(steps))
if __name__ == "__main__":
main(sys.argv[1:])
In your code you have
if opt == ("-m", "--min"):
which should be
if opt in ("-m", "--min"):
Since you had that right on all the other places, I guess this was just forgotten there.

Categories

Resources