I want to pass a value into my python script, as shown in the below image
Where, xyz would be my python file which requires the abc value.
How do I do this and access the abc value in xyz.py?
You can try like this,
#!/usr/bin/python
import sys
print 'Argument List:', str(sys.argv)
The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purpose:
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Example: Consider the following script test.py:
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Now run above script as follows:
$ python test.py arg1 arg2 arg3
This will produce following result:
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
you can use sys.argv
but better approach is to use argparse module.
here is an example.
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(prog='reader', description='Read commandline value.')
parser.add_argument('-v', '--value')
args = parser.parse_args()
print "Value you entered: %s" % args.value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.