如何让Python程序将参数作为来自UNIX终端标准输入的输入?

Inq*_*Kea 0 python

例如 - 我想做点什么......

python DoublePendulum.py INPUT1 INPUT2

(其中INPUT1和INPUT2作为DoublePendulum程序中的变量输入).

ava*_*sal 5

$ python test.py arg1 arg2 arg3
Run Code Online (Sandbox Code Playgroud)

在test.py中

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Run Code Online (Sandbox Code Playgroud)

产量

Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Run Code Online (Sandbox Code Playgroud)

Python还提供了可帮助您解析命令行选项和参数的模块.标准库中有以下模块:

  • getopt的模块类似于GNU getopt的.
  • optparse模块提供面向对象的命令行选项解析,optparse被弃用版本的Python 2.7 argparse是更换.