After running the code, the error is as follows:
usage: text-summarizer.py [-h] [-l LENGTH] filepath
text-summarizer.py: error: the following arguments are required: filepath
I want to solve this issue by knowing how to input the file name to this piece of code mentioned :
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("filepath", help="File name of text to summarize")
parser.add_argument(
"-l", "--length", default=4, help="Number of sentences to return"
)
args = parser.parse_args()
return args
When you run the code from the console just write
python text-summarizer.py 'path/to/file'
or if you use python3:
python3 text-summarizer.py 'path/to/file'
where `path/to/file' is actually the path (on your computer) that you want to summarize
Related
I have written a code function.py in python which has input file path and a output file path and some flags . currently I have hardcoded everything.I want to use command line arguments to provide these inputs so that anyone can run my script by providing input to cmd.how can I do it in python?
In CMD
function.py "input file path" "output file path"
A very rudimentary example would be:
import sys
input_file_path = sys.argv[1]
output_file_path = sys.argv[2]
Note that sys.argv[0] would be your filename. You should also do the relevant checks to make sure there are the correct number of arguments, whether they are valid, etc.
As an alternative to sys.argv, I prefer argparse.
As an example:
# Import the argparse module
import argparse
# Define a function to use argparse to parse your command-line arguments
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input-file",
dest="input_file",
help="File to use as input",
type=str
)
parser.add_argument(
"-o",
"--output-file",
dest="output_file",
help="File to output to",
type=str
)
return parser.parse_args()
# If calling this module from the command line, this `if` statement will evaluate to True
if __name__ == "__main__":
# Parse your command-line arguments
args = parse_args()
# Get the parsed value of the "-i" argument:
infile = args.input_file
# Get the parsed value of the "-o" argument:
outfile = args.output_file
I am trying to set up training arguments and parse but I got this error could anyone help please!
parser = argparse.ArgumentParser(description='Explore pre-trained AlexNet')
parser.add_argument(
'--image_path', type=str,
help='Full path to the input image to load.')
parser.add_argument(
'--use_pre_trained', type=bool, default=True,
help='Load pre-trained weights?')
args = parser.parse_args()
got this error
usage: ipykernel_launcher.py [-h] [--image_path IMAGE_PATH]
[--use_pre_trained USE_PRE_TRAINED]
ipykernel_launcher.py: error: unrecognized arguments: -f /root/.local/share/jupyter/runtime/kernel-ff8e2476-e39b-4e40-b8f9-6b8113fe8f1f.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
In a Jupyter notebook cell:
import sys
sys.argv
I get get
['/usr/local/lib/python3.8/dist-packages/ipykernel_launcher.py',
'-f',
'/home/paul/.local/share/jupyter/runtime/kernel-7923bfd2-9f96-45cf-8b44-1859a2185715.json']
The Jupyter server is using the sys.argv to set up the communication channel with your kernel. argparse parses this list too.
So commandline and argparse cannot be used to provide arguments to your notebook when run this way.
How did you start this script? Did you even try to provide the commandline values that the script expected?
'--image_path'
'--use_pre_trained'
If you did, you probably would have gotten a different parser's error, about 'unexpected arguments'. That's coming from the server.
If you use a Colab may this solution help you, this solution suggest to you to write argparse in the other python file introduction-argparse-colab
%%writefile parsing.py
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
In a Jupyter notebook code works like this:
parser = argparse.ArgumentParser()
parser.add_argument('--image_folder', type=str, default='/content/image', help='path to image folder')
parser.add_argument("-f", "--file", required=False)
You need to add in the end of " parser.add_argument " line ( This is the reason you are getting 'SystemExit: 2' error ):
parser.add_argument("-f", required=False)
in your case this should work:
parser = argparse.ArgumentParser(description='Explore pre-trained AlexNet')
parser.add_argument('--image_path', type=str, default='your_path', help='Full path to the input image.')
parser.add_argument('--use_pre_trained', type=bool, default=True, help='Load pre-trained weights?')
parser.add_argument("-f", "--file", required=False)
args = parser.parse_args()
Now you can call:
image = args.image_path
Or
from PIL import Image
image = Image.open(args.image_path)
Tested in Google colab
I would like to execute a code which is accessible from this link.
The code objective is to read and extract the pdf annotation.
However, I am not sure how to direct the pdf file path using the argparse, which I suspect, should be the following argparse.
p.add_argument("input", metavar="INFILE", type=argparse.FileType("rb"),
help="PDF files to process", nargs='+')
Say, I know the absolute path of the pdf file is as follow;
C:\abc.pdf
Also, given that I still try to comprehend the code, so I would like to avoid re-enter the path C:\abc.pdf over and over again. Is there are way, I can temporary hard coded it within the def parse_args()
I have read several thread about this topic, however, still having difficulties in comprehend about this issue.
Thanks in advance for any insight.
You add the argument to a parser:
import argparse
p = argparse.ArgumentParser()
p.add_argument("input", metavar="INFILE", type=argparse.FileType("rb"),
help="PDF files to process", nargs='+')
args = p.parse_args()
Then args.input will be a tuple of one or more open file handles.
If you're running pdfannots.py from the command prompt, then you do so as, e.g.,
python pdfannots.py C:\abc.pdf
If you want to run it over multiple PDF files, then you do so as, e.g.,
python pdfannots.py C:\abc.pdf D:\xyz.pdf E:\foo.pdf
If you really want to hard code the path, you'll have to edit pdfannots.py as follows:
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
# p.add_argument("input", metavar="INFILE", type=argparse.FileType("rb"),
# help="PDF files to process", nargs='+')
g = p.add_argument_group('Basic options')
g.add_argument("-p", "--progress", default=False, action="store_true",
help="emit progress information")
g.add_argument("-o", metavar="OUTFILE", type=argparse.FileType("w"), dest="output",
default=sys.stdout, help="output file (default is stdout)")
g.add_argument("-n", "--cols", default=2, type=int, metavar="COLS", dest="cols",
help="number of columns per page in the document (default: 2)")
g = p.add_argument_group('Options controlling output format')
allsects = ["highlights", "comments", "nits"]
g.add_argument("-s", "--sections", metavar="SEC", nargs="*",
choices=allsects, default=allsects,
help=("sections to emit (default: %s)" % ', '.join(allsects)))
g.add_argument("--no-group", dest="group", default=True, action="store_false",
help="emit annotations in order, don't group into sections")
g.add_argument("--print-filename", dest="printfilename", default=False, action="store_true",
help="print the filename when it has annotations")
g.add_argument("-w", "--wrap", metavar="COLS", type=int,
help="wrap text at this many output columns")
return p.parse_args()
def main():
args = parse_args()
global COLUMNS_PER_PAGE
COLUMNS_PER_PAGE = args.cols
for file in [open(r"C:\Users\jezequiel\Desktop\Timeline.pdf", "rb")]:
(annots, outlines) = process_file(file, args.progress)
pp = PrettyPrinter(outlines, args.wrap)
if args.printfilename and annots:
print("# File: '%s'\n" % file.name)
if args.group:
pp.printall_grouped(args.sections, annots, args.output)
else:
pp.printall(annots, args.output)
return 0
Here's what I'm trying to accomplish:
When passing a string as the arg, call a write_text() function
python3 app.py write this text to file
When passing a dashed arg, call another function, in this case read_text()
python3 app.py -r
When passing no args print help
python3 app.py
Here's what I have so far:
parser = argparse.ArgumentParser()
parser.add_argument('text', help="write text to file")
parser.add_argument('-r', '--read', help="read text from file")
args = parser.parse_args()
...
def main():
if args.read:
read_text()
elif args.text:
write_text(args.text)
else:
parser.print_help()
The problem is that when I call just -r it complains that it's missing a command for text, because text is not an optional argument.
I've tried creating subcommands and making all the args subcommands but then the text argument needs to be explicitly called like python3 app.py text.
I may be thinking too hard on this and overlooking a simple solution. I had this working perfectly just parsing sys.argv, but it wasn't pretty. And the built in help function is useful as well.
Thanks in advance!
Edit:
Here's what I have now that's working
parser = argparse.ArgumentParser()
parser.add_argument('text', nargs='*', help="write text to file")
parser.add_argument('-r', '--read', action='store_true', help="read text from file")
args = parser.parse_args()
...
def main():
if args.read:
read_text()
elif args.text:
text = " ".join(args.text)
write_text(text)
else:
parser.print_help()
Still thinking there may be a cleaner way to do this...
This might help :
parser.add_argument('text', nargs='?', help="write text to file")
more info : https://docs.python.org/3/library/argparse.html#nargs
Note that you should use action='store_true' for the read argument if you want to use args.read as a boolean later.
parser.add_argument('-r', '--read', action='store_true', help="read text from file")
I have a script saved as workspace.py
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('title', type=str, help="Will be displayed as the title")
parser.add_argument('-f', '--folder', help='Point to the folder you want to read from (defaults to current folder in command prompt)', type=str, default=os.getcwd())
args = parser.parse_args()
print(args)
someFunction(args.folder, args.title)
Which I call from terminal with:
workspace.py myTitle
Resulting in the error
workspace.py: error: the following arguments are required: title
I have no idea why this is happening because I supply "myTitle" in the terminal. If I specify a default= for the title argument it works perfectly with that value. The part that is throwing me is it doesn't even get to the print(args) so I cannot see what the program thinks is what, but instead fails at args = parser.parse_args()
I tried to even redo the exact example at: https://docs.python.org/2/howto/argparse.html#introducing-positional-arguments (copied below)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print args.echo
Running
workspace.py hello
Results in (after adding parenthesis to the print for 3.X)
workspace.py: error: the following arguments are required: echo
Is there something I'm missing? Why does it not just print "hello"? Is there some Python 3 specific syntax I'm missing or something?
I've gotten it to work if I run python workspace.py someString instead of workspace.py someString. I do not understand why this version works, since command prompt obviously recognizes it as Python and runs it correctly until args = parser.parse_args(). There were no errors like 'workspace.py' is not recognized as an internal or external command, operable program or batch file. There was no problem importing modules either. Consider the below command prompt session if you are running into a similar error. Maybe you will simply have to include python in your commands like I have to...
C:\Users\rparkhurst\PycharmProjects\Workspace>workspace.py MyTitle
usage: workspace.py [-h] [-f FOLDER] title
workspace.py: error: the following arguments are required: title
C:\Users\rparkhurst\PycharmProjects\Workspace>python workspace.py MyTitle
Namespace(folder='C:\\Users\\rparkhurst\\PycharmProjects\\Workspace', title='MyTitle')