How to pass command line arguments in Python 3.x?

前端 未结 2 1999
心在旅途
心在旅途 2020-12-30 00:41

I am not getting desired output of this program?

from sys import argv

script, first, second, third = argv

print (\"The script is called:\", script)
print (         


        
相关标签:
2条回答
  • 2020-12-30 00:59

    You can use import argparse from here: https://docs.python.org/3/howto/argparse.html

    0 讨论(0)
  • 2020-12-30 01:12

    You call it like

    python program.py a1 b2 c3
    

    and it outputs

    The script is called: /home/sophia/program.py
    Your first variable is: a1
    Your second variable is: b2
    Your third variable is: c3
    

    sys.argv contains list of strings, each corresponding to a command line parameter. First one is always the filename of the script; others are the optional parameters, ordered exactly as they were typed in a shell.

    Note that the code you provided works correctly only when you pass exactly three parameters due to the tuple unpacking.

    See the docs for sys.argv and also check out argparse module documentation if you are going to write a program handling lots of arguments.

    0 讨论(0)
提交回复
热议问题