python 来自文件的脚本命令行参数

python script command line arguments from file

test.txt

port = 1234

host = abc.com

test.py

port = sys.argv[1]

host = sys.argv[2]

我想提供 test.txt 作为 python 脚本的输入:

python test.py test.txt

以便文本文件中的 、端口和主机值应作为命令行参数传递给 python 脚本,这些脚本又传递给脚本中的端口和主机。

如果我这样做:

python test.py 1234 abc.com

参数传递给 sys.argv[1] 和 sys.argv[2]

我想通过读取 txt 文件实现同样的效果。

谢谢。

Linux 中的一种方法是:

 awk '{print }' test.txt | xargs python test.py

您的 .txt 文件可以分为 3 列,其中第 3 列包含端口和主机的值。 awk '{print }' 提取这些列并 xargs 将它们作为输入参数提供给您的 python 脚本。

当然,前提是您不想修改 .py 脚本来读取文件并提取那些输入值。

给定一个包含 header 部分的 test.txt 文件:

[settings]
port = 1234
host = abc.com

您可以使用 ConfigParser 库获取主机和端口内容:

import sys
import ConfigParser

if __name__ == '__main__':
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])
    print config['settings']['host']
    print config['settings']['port']

在 Python 3 中称为 configparser(小写)。

我只想将文本文件写成:

1234
abc.com

那么你可以这样做:

input_file = open(sys.argv[1])
port = int(input_file.readLine())
host = input_file.readLine()