7

test.txt

port = 1234

host = abc.com

test.py

port = sys.argv[1]

host = sys.argv[2]

I want to provide test.txt as input to python script:

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.

if i do :

python test.py 1234 abc.com

the arguments are passed to sys.argv[1] and sys.argv[2]

the same i want to achieve using reading from txt file.

Thanks.

2
  • 2
    And your problem is...? Commented Feb 9, 2015 at 22:09
  • 1
    i want solution, how to do it. modified my question. Commented Feb 9, 2015 at 22:12

3 Answers 3

12

Given a test.txt file with a section header:

[settings]
port = 1234
host = abc.com

You could use the ConfigParser library to get the host and port content:

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).

Sign up to request clarification or add additional context in comments.

3 Comments

This worked with small change: config.get("settings","appport"). Thanks.
@lgor Hatarist I am getting "IndexError: list index out of range" error, if I run the above script. Unable to figure out the issue.
@Kumar It's because when you run it, you don't pass an argument to the command. Run it using python script.py test.txt, not just python script.py. You could figure it out by reading about sys.argv in the python's documentation).
1

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()

1 Comment

This also worked but after replacing port value in a file, the rest of string in the line of file is moving to next line. But, thanks though.
1

A way to do so in Linux is to do:

 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. awk '{print $3}' extracts those column and xargs feeds them as input parameters to your python script.

Of course, that is only if you don't want to modify your .py script to read the file and extract those input values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.