can't pass arguements using argparse and pytho

2019-08-12 16:03发布

I've upgraded to Python 3.4.2 and argparse (from optparse) but neither appears to recognise command line options. As a simple test I run this;

#test_argparse.py

def main():
    import argparse

    parser = argparse.ArgumentParser(description='Execute database query.')

    parser.add_argument("-q", "--query", dest="query",
                  help="Name of the query file to be run")

    args = parser.parse_args()

    print(args)

if __name__ == '__main__':
     main()

From the command line, when I run

test_argparse.py -q get_msre_for_book

I get:

Namespace(query=None)

But when I run from within the IDE:

*** Python 3.4.2rc1 (v3.4.2rc1:8711a0951384, Sep 21 2014, 21:16:45) [MSC v.1600 32 bit (Intel)] on win32. ***

Command Line : -q get_msre_for_book
Namespace(query='get_msre_for_book')

I'm trying to launch the script via

os.system('python.exe', '<path to script>test_argparse.py -q get_msre_for_book')

But that fails as no query is presented as shown above. I've worked round this by launching using

subprocess.call

but I'd rather not have to. Again, any suggestions or ideas gratefully received.

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-12 16:24

To give closure to this question, these are the 2 comments that solve the problem:

There are earlier SO questions about passing commandline arguments in Windows 7. The solutions involve getting a registry link right. stackoverflow.com/questions/2640971, stackoverflow.com/questions/9880540. e,g, "C:\Python\Python33\python.exe" "%1" %*.

That fixed it - thank you very much - but to be precise the registry entry needs to be C:\Python\Python33\python.exe" "%1" %" (added the final double quote)

查看更多
登录 后发表回答