2

I am passing a single, positional argument string called FILE, but when no arguments are passed, I want it to print a usage statement.

Every time I write './files.py' in my command-line with no arguments after it, my code does nothing. What am I doing wrong?

import argparse
import re

#--------------------------------------------------
def get_args():
    """get arguments"""
    parser = argparse.ArgumentParser(
        description='Create Python script',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('FILE', help='Pass a file', type=str)

    return parser.parse_args()

#--------------------------------------------------

def main():
    """main"""
    args = get_args()
    FILE = args.FILE.IGNORECASE()

    if len(args) != 1:
        print("Usage: files.py {}".format(FILE))
        sys.exit(1)

# --------------------------------------------------
if __name__ == '__main__':
    main()

Expected outcome:

$ ./files.py
Usage: files.py FILE

What I am getting:

$./files.py
$
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
kevin
  • 29
  • 4
  • I don't think the only issue was calling the `main()` method. – DirtyBit Apr 02 '19 at 06:57
  • What happens if you do provide arguments? – MisterMiyagi Apr 02 '19 at 07:01
  • Mod's should consider opening this question, so substantial answers can be posted, cheers! – DirtyBit Apr 02 '19 at 07:01
  • Like OP stated, *I have main() added in my own code, I just forgot to add it in this question.* PS. I could post an answer that would very likely solve his problem! :D – DirtyBit Apr 02 '19 at 07:05
  • 1
    I am still not getting a usage statement printed. I just get nothing returned when I run './files.py'. Also, I have called the main() function at the end of my code. – kevin Apr 02 '19 at 07:12
  • @DirtyBit As the question currently stands, adding ``main()`` *does* solve the problem. If there is a different problem, the question must be edited to make clear which problem it is. – MisterMiyagi Apr 02 '19 at 07:14
  • @kevin Edit your question, add the missing part with the output you're getting and desired. – DirtyBit Apr 02 '19 at 07:15
  • @kevin Should'nt the output you're getting be: `usage: test.py [-h] FILE test.py: error: the following arguments are required: FILE`? – DirtyBit Apr 02 '19 at 07:23
  • @keving Do you have a shebang at the start of your script? If not, do you get any non-python error message, say ``import: missing an image filename `import' @ error/import.c/ImportImageCommand/1302.``? – MisterMiyagi Apr 02 '19 at 07:28
  • Yes I have included '#!/usr/bin/env python3' at the top of my script and my code doesn't return any errors. I am just confused why it is not returning the usage statement. @MisterMiyagi – kevin Apr 02 '19 at 07:31
  • Do you get *any* output from the script in any situation? Do ``print`` statements outside of functions work? What happens if you do provide arguments? – MisterMiyagi Apr 02 '19 at 10:42
  • After the edit, the problem appears not to be reproducible. – Karl Knechtel Oct 01 '22 at 18:27

3 Answers3

0

You never run main...

import argparse
import re
#--------------------------------------------------
def get_args():
    """get arguments"""
    parser = argparse.ArgumentParser(
        description='Create Python script',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('FILE', help='Pass a file', type=str)
return parser.parse_args()
#--------------------------------------------------
def main():
    """main"""
    args = get_args()
    FILE = args.FILE.IGNORECASE()
    if len(args) != 1:
        print("Usage: files.py {}".format(FILE))
        sys.exit(1)
main()
vi_me
  • 373
  • 4
  • 17
  • 1
    I have main() added in my own code, I just forgot to add it in this question, but I still encounter the same problem I stated above. – kevin Apr 02 '19 at 06:56
  • My output...` ~ python3 test.py` `usage: test.py [-h] FILE` `test.py: error: the following arguments are required: FILE` – vi_me Apr 02 '19 at 06:58
  • @kevin That behaviour is not reproducible with the code you have shown. Please provide a complete and verifiable example. – MisterMiyagi Apr 02 '19 at 07:01
0

You need to define the entry point of your code. If you want to call this as you are describing (./files.py) you need to define the main entry point like this:

if __name__ == "__main__":
    """main"""
    args = get_args()
    FILE = args.FILE.IGNORECASE()

    if len(args) != 1:
        print("Usage: files.py {}".format(FILE))
        sys.exit(1)
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
0

You have to tell your operating system that the script must be executed by Python. Add a shebang as the first line of your script:

#!/usr/bin/env python3
import argparse
...

Otherwise, you have to explicitly execute the script with Python:

python3 ./files.py

You must call your main function. A good place is at the end of the script, guarded to be run on execution only:

if __name__ == '__main__':  # do not run on import
    main()

This gives the desired output:

$ python3 so_script.py
usage: so_script.py [-h] FILE
so_script.py: error: the following arguments are required: FILE

Note that argparse already creates the usage and help messages for you. There is no need to create them yourself. In fact, argparse will end your script before your own usage information is run.

If you do not want to have the -h switch, pass add_help=False when creating the argument parser.

parser = argparse.ArgumentParser(
    description='Create Python script',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    add_help=False,
)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • 1
    I have the main() function called, but I still get nothing. Also, I don't want it to return [-h] if that's possible. – kevin Apr 02 '19 at 07:03
  • @kevin With the code you have postet, missing ``main`` is the only problem. We cannot guess what *additional* parts you have not shown to produce another problem. Please edit your question to include the minimal code required to reproduce your problem. – MisterMiyagi Apr 02 '19 at 07:11
  • @kevin You might be missing a shebang, but in that case you should still get errors from the Shell trying to make sense of your Python code. – MisterMiyagi Apr 02 '19 at 07:29