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.
-
2And your problem is...?mgilson– mgilson2015年02月09日 22:09:12 +00:00Commented Feb 9, 2015 at 22:09
-
1i want solution, how to do it. modified my question.bvr– bvr2015年02月09日 22:12:49 +00:00Commented Feb 9, 2015 at 22:12
3 Answers 3
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).
3 Comments
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).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
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.