简体   繁体   中英

How to pass a parameter via CMDline in Python Script

I have a python script that looks like this:

a='{}'

From my cmdline i want to be able to pass a parameter for that value in the brackets. So:

python- my_script.py Hello World

The output would then be:

'Hello World'

Any ideas or suggestion as to how to pass a parameter on the command line in a python script when running it? I am new to python so any tips would help!

Reference here !

I'm also fairly new to Python so not 100% positive this works but assuming it does, To recreate what your searching for.

#!/usr/bin/python

import sys

print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

After adding the Import sys

Where your python my_script.py 'Hello World'

Note that:

my_script.py equals sys.argv[0]

'Hello World' equals sys.argv[1]

Therefore setting a = sys.argv[1] should work!

To test it try to print(a)

Also note that this will not work if your cmdline is python my_script.py Hello World This will treat Hello and world as two separate arguments.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM