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.
In Python getting arguments from the command line to a script is quite easy. Before you can pass arguments to a script, you’ll need to understand how to run a Python script from the command line. Follow this tutorial for a step-by-step guide. In Python, arguments are passed to a script from the command line using the sys package.
The command-line arguments are used to provide specific inputs to the program. What is the benefit of Python Command Line Arguments? Python command-line arguments help us to keep our program generic in nature.
You’ll write another script to demonstrate that, on Unix-like systems, Python command line arguments are passed by bytes from the OS. This script takes a string as an argument and outputs the hexadecimal SHA-1 hash of the argument:
print('Fourth argument:', str(sys.argv[3])) Then execute the above script with command line parameters. python script.py first 2 third 4.5 You will see the results like below. The first argument is always the script itself.
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).
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With