Reputation: 259
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.
Upvotes: 7
Views: 21983
Reputation: 2826
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.
Upvotes: 1
Reputation: 930
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()
Upvotes: 1
Reputation: 5442
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).
Upvotes: 12