Python url title problem - python

import lxml.html, sys
for arg in sys.argv:
url2 = arg
t = lxml.html.parse(url2)
if arg == "":
url = raw_input("Website URL: ")
t = lxml.html.parse(url)
print t.find(".//title").text
Problem is with [if arg == "":]
I want to have something like "if there is no arg, then:", but I don't know how.
How can I do that?

Try this:
if len(sys.argv) == 1:
print 'no arg'
Edit: There is one more issue in your code:
for arg in sys.argv:
...
Should be:
for arg in sys.argv[1:]:
...
since the first argument is the python file name itself

Related

Pytest assert if sys. argv == something it will run a function

I'm trying to test the main function that if len (sys. argv) < 1 or len (sys. argv) < 4 it will run a function using pytest
this is my main fucntion
def main():
if len(sys.argv) == 1:
print(print_help())
elif len(sys.argv) == 2 or len(sys.argv) == 3:
if sys.argv[1] == 'help' or sys.argv[1] == 'h' or sys.argv[1] == 'H':
print(print_help())
else:
print('no such command arguments try python project.py help')
def print_help:
the_help = 'the help section'
return the_help
if __name__ =='__main__':
main()
How can I use pytest to test this main function if sys. argv < 1 that it will run the print_help function
or if sys.argv == 'help' or sys.argv == 'h' or sys.argv == 'H' it will run the same fucntion
My preferred approach is make your main() function take its inputs from a variable instead of from sys.argv directly:
def main(args):
if len(args) == 1:
print(print_help())
elif len(args) == 2 or len(args) == 3:
if args[1] == 'help' or args[1] == 'h' or args[1] == 'H':
print(print_help())
else:
print('no such command arguments try python project.py help')
def print_help:
the_help = 'the help section'
return the_help
if __name__ =='__main__':
main(sys.argv)
Now you can use capsys in your test function to test the output, and can easily pass in whatever list of arguments you want to test without having to patch or mock anything.
Also, argparse does this sort of command line processing for you. I highly, highly recommend using it (or other similar libraries) instead of re-inventing the wheel.
I find some kind of answer that helps a little bit
I find it on this Github link
def test_main(capsys):
from project import main
sys.argv = ['h', 'H', 'help']
main()
out, err = capsys.readouterr()
assert out.startswith("the help section") is True
it check if the output of the print_help is the same as entering one of the commands in sys.argv= ['h', 'H', 'help']

Index out of range when using more than one sys.argv when using if statements

Here is my work so far, I keep getting this error, but I cannot figure out how to solve it.
all = sys.argv[1]
help = sys.argv[2]
if sys.argv[1] >=1:
print("Test")
else:
print 'Test'
if sys.argv[1] >=2:
print("Test2")
else:
print 'Test2'
By default you have only one item(with index 0) in sys.argv, and it is name of your script. To avoid IndexError try to check that arguments actually passed to your script:
if len(sys.argv) > 1:
# check what sys.argv[1] is

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)

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.

Filtering integers out of python command line arguments

so I wrote a program and I want to pass it either a filename and an integer or just an integer. Whats the best way to determine which argument is the integer? This is what I have:
import sys
if len(sys.argv) > 1):
for e in sys.argv:
try:
bio = map(e, int)
except:
pass
thanks in advance
You could check whether or not the argument is an integer with the string isdigit() method:
import sys
if len(sys.argv) > 1:
for e in sys.argv:
if e.isdigit():
# all characters in e are digits and there is at least one character in e
else:
# it is possibly your filename argument
But, I should encourage you to give a chance to the argparse library: http://docs.python.org/dev/library/argparse.html
import argparse
parser = argparse.ArgumentParser(description = 'A simple description')
parser.add_argument('-f', action = 'store', dest = 'filename', required = False)
parser.add_argument('-n', action = 'store', dest = 'n', required = True, type=int)
arguments = parser.parse_args()
print arguments.n
print arguments.filename
def isint(val):
try:
int(val)
return True
except:
return False
int_args = filter(isint,sys.argv)
not_int_args = set(sys.argv) - set(int_args)
if len(sys.argv) == 1: #user passed in only one argument. It must be an integer.
bio = int(sys.argv[0])
elif len(sys.argv) == 2: #user passed in two arguments: filename and integer.
filename = sys.argv[0]
bio = int(sys.argv[1])
else: #user didn't pass in the right number of arguments
raise Exception("Expected one or two arguments")

Categories

Resources