内联python脚本的命令行参数?

2024-03-29 11:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一套comman行工具,作为bash函数实现,例如:

function sf
{
    sftp $(svr $1)
}

其中svr是另一个将短名称转换为完全限定域名的函数。我想把这个函数转换成:

function irpt
{
    ~/tools/icinga_report $*
}

例如:

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

这非常有效,除了一件事:我需要在某个地方添加参数,但是我看不到在哪里。我曾尝试将整个python块括在{ }中,但不起作用:

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

shell不接受以下定义:

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

有什么办法可以实现吗? ===编辑=== 受到我接受的答案的启发,这就是我所做的,也许对其他人有用:

function irpt
{
python <<!
import requests

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

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

这个很好用。你知道吗


Tags: 工具of函数importbashlineetcfunction
3条回答

看起来有点奇怪,但是可以使用bash <(command)语法动态地提供一个脚本文件(实际上是一个命名管道);其余的如下所示。你知道吗

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

你可以用这样的东西

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

或者

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

然后使用如下函数

foo test

单向:

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

运行函数:

$ irpt hello
hello
$

相关问题 更多 >