Home > OS >  How can we pass argument in single line python command
How can we pass argument in single line python command

Time:09-03

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?

CodePudding user response:

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.

CodePudding user response:

You can use sys.argv[] like :

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

output:

test
  • Related