9: Command Line Arguments(Command line Python scripting)

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  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值