简体   繁体   中英

How can we pass argument in single line python command

I using below command for get json data:

cat config.json | python -c 'import json,sys;obj=json.load(sys.stdin); print obj['prd']['vmname']

Above command parse json with static value, here I want to make dynamic with pass the 'prd' and based on this print it.

I tried as below but not worked:

# env="prd"
# cat config.json | python ${env} -c 'import json,sys;obj=json.load(sys.stdin); print obj[sys.argv[1]]['vmname']

How to pass 'prd' as variable in this command?

You need to pass the argument after the -c switch:

cat config.json | python -c "import json,sys;obj=json.load(sys.stdin); print(obj[sys.argv[1]]['vmname'])" "prd"

The string prd will be passed as sys.argv[1] in the script.

You can use sys.argv[] like:

python  -c "import sys; print(sys.argv[1])" 'test'

output:

test

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