【问题标题】:python script command line arguments from file来自文件的python脚本命令行参数
【发布时间】:2015-02-09 22:07:20
【问题描述】:

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 文件来达到同样的效果。

谢谢。

【问题讨论】:

  • 你的问题是……?
  • 我想要解决方案,该怎么做。修改了我的问题。

标签: python python-2.7 python-3.x


【解决方案1】:

给定一个带有节标题的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(小写)。

【讨论】:

  • 这只需少量更改即可:config.get("settings","appport")。谢谢。
  • @lgor Hatarist 如果我运行上述脚本,我会收到“IndexError: list index out of range”错误。无法解决问题。
  • @Kumar 这是因为当你运行它时,你没有将参数传递给命令。使用python script.py test.txt 运行它,而不仅仅是python script.py。你可以通过阅读python文档中的sys.argv来弄清楚)。
【解决方案2】:

我只想将文本文件写为:

1234
abc.com

那么你可以这样做:

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

【讨论】:

  • 这也有效,但是在替换文件中的端口值后,文件行中的其余字符串将移动到下一行。不过,谢谢。
【解决方案3】:

在 Linux 中这样做的一种方法是:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2013-07-29
    • 2012-01-24
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多