j4nd3r53n
j4nd3r53n

Reputation: 850

Command line parameters for an inline python script?

I have a set of comman-line tools that I implement as bash functions, eg:

function sf
{
    sftp $(svr $1)
}

where svr is another function that translates a short name to a fully qualified domain name. I got the idea that I wanted to convert this function:

function irpt
{
    ~/tools/icinga_report $*
}

to something like:

function irpt
{
python <<!
import requests
...lots of python stuff...
!
}

This works perfectly, except for one thing: I need to add the parameters somewhere, but I can't see where. I have tried to enclose the whole python block in { }, but it doesn't work:

function irpt
{
python <<!
import requests
...lots of python stuff...
!
} 

The shell doesn't accept the definition:

-bash: /etc/profile: line 152: syntax error near unexpected token `$*'
-bash: /etc/profile: line 152: `} $*'

Is there any way to implement this? ===EDIT=== Inspired by the answer I accepted, this is what I did, maybe it is useful for others:

function irpt
{
python <<!
import requests

param="$*".split(' ')

...lots of python stuff...
!
}

This works beautifully.

Upvotes: 1

Views: 1055

Answers (3)

D. Jones
D. Jones

Reputation: 481

You can use something like this

foo() {
cmd=$(cat <<EOF
print("$1")
EOF
)
python -c "$cmd"
}

Alternatively,

foo() {
python -c $(cat <<EOF
print("$1")
EOF
)
}

And then use the function like

foo test

Upvotes: 0

Guru
Guru

Reputation: 17024

One way:

function irpt
{
python <<!
import requests
v1='$1'
print(v1)
!
}

Running the function:

$ irpt hello
hello
$

Upvotes: 3

alexis
alexis

Reputation: 50220

It looks a little weird, but you can use the bash <(command) syntax to provide a script file dynamically (in reality, a named pipe); the rest follows.

function demo {
    python <(echo 'import sys; print(sys.argv)') "$@"
}

Upvotes: 2

Related Questions