9: Command Line Arguments(Command line Python scripting)

    xiaoxiao2022-06-27  35

    You can also pass command line options into Python scripts. They can be retrieved inside the script using the sys package. The argv list allows you to retrieve the positional arguments passed into the script. We learned about positional arguments in the last mission -- they are any arguments that come after the command name. An example is python script.py 82. The first positional argument is script.py, and the second is 82.

    import sys if __name__ == "__main__": print ( sys. argv [ 1 ])

    The above code will read input from the command line, and print it back out. If the code is saved to script.py, you'd call python script.py "Hello from the command line" to pass in the text you want displayed.

    You'll notice that we print the second item in theargv list (sys.argv[1]). This is because the arguments start after the python command, so the first argument is the name of the file we want to run. The second argument is the actual text that we want to print.

    Instructions

    Modify script.py to accept and print a command line argument.

    Then, call the script and pass in "Hello from the command line" (python3) /home/dq$ echo -e 'import sys\nif __name__=="__main__":\n    print(sys .argv[1])'>script.py                                                             (python3) /home/dq$ python script.py "Hello from the command line"               Hello from the command line  

    转载请注明原文地址: https://ju.6miu.com/read-1124040.html

    最新回复(0)