简体   繁体   中英

Passing arguments to a embedded python script in bash

I'm having difficulties passing arguments to a embedded bash script.

 #!/bin/bash/
 function my_function() {
 MYPARSER="$1" python - <<END
 <<Some Python Code>>

 class MyParser(OptionParser):
 def format_epilog(self, formatter):
    return self.epilog

 parser=MyParser(version=VER, usage=USAGE, epilog=DESC)

 parser.add_option("-s", "--Startdir", dest="StartDir", 
               metavar="StartDir"
             )
 parser.add_option("-r", "--report", dest="ReportDir", 
               metavar="ReportDir"
             )
<<More Python Code>>

 END
 }

 foo="-s /mnt/folder -r /storagefolder/"
 my_function "$foo"   

I've read Steve's Blog: Embedding python in bash scripts which helped but I'm still unable to pass the argument. I've tried both parser and myparser as environmental variables.

Is it as simple as defining $2 and passing them individually?

Thanks

You're overcomplicating this rather a lot. Why mess with a parser where

value="hello" python -c 'import os; print os.environ["value"]'

Or, for a longer script:

value="hello" python <<'EOF'
import os
print os.environ["value"]
EOF

If you need to set sys.argv for compatibility with existing code:

python - first second <<<'import sys; print sys.argv'

Thus:

args=( -s /mnt/folder -r /storagefolder/ )
python - "${args[@]}" <<'EOF'
import sys
print sys.argv # this is what an OptionParser will be looking at by default.
EOF

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