简体   繁体   English

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

[英]python script command line arguments from file

test.txt 的test.txt

port = 1234

host = abc.com

test.py test.py

port = sys.argv[1]

host = sys.argv[2]

I want to provide test.txt as input to python script: 我想提供test.txt作为python脚本的输入:

python test.py test.txt

so that , port and host values in text file should pass as command line arguments to python script which are inturn passed to port and host in the script. 因此,文本文件中的端口和主机值应作为命令行参数传递给python脚本,这些参数将被传递到脚本中的端口和主机。

if i do : 如果我做 :

python test.py 1234 abc.com python test.py 1234 abc.com

the arguments are passed to sys.argv[1] and sys.argv[2] 参数传递给sys.argv [1]和sys.argv [2]

the same i want to achieve using reading from txt file. 同样我想用txt文件读取来实现。

Thanks. 谢谢。

Given a test.txt file with a section header: 给定带有节头的test.txt文件:

[settings]
port = 1234
host = abc.com

You could use the ConfigParser library to get the host and port content: 您可以使用ConfigParser库来获取主机和端口内容:

import sys
import ConfigParser

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

In Python 3 it's called configparser (lowercase). 在Python 3中,它被称为configparser (小写)。

A way to do so in Linux is to do: 在Linux中这样做的方法是:

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

Your .txt file can be separated in 3 columns, of which the 3rd contains the values for port and host. 您的.txt文件可以分为3列,其中第3列包含端口和主机的值。 awk '{print $3}' extracts those column and xargs feeds them as input parameters to your python script. awk '{print $3}'提取那些列, xargs将它们作为输入参数提供给python脚本。

Of course, that is only if you don't want to modify your .py script to read the file and extract those input values. 当然,只有当您不想修改.py脚本来读取文件并提取这些输入值时。

I would instead just write the text file as: 我只想把文本文件写成:

1234
abc.com

Then you can do this: 然后你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM