My .profile
定义一个函数
myps () {
ps -aef|egrep "a|b"|egrep -v "c\-"
}
我想从我的 python 脚本执行它
import subprocess
subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True)
返回错误
bash: -c: line 0: syntax error near unexpected token `;'
bash: -c: line 0: `; myps'
逃跑;结果是
bash: ;: command not found
script='''
. ~/.profile # load local function definitions so typeset -f can emit them
ssh user@box ksh -s <<EOF
$(typeset -f)
myps
EOF
'''
import subprocess
subprocess.call(['ksh', '-c', script]) # no shell=True
这里有一些相关的项目:
-
定义该函数的dotfile需要在本地调用before你跑typeset -f
通过网络转储函数的定义。默认情况下,非交互式 shell 不会运行大多数点文件(任何由ENV
环境变量是一个例外)。
在给定的示例中,这是由. ~/profile
脚本中的命令。
-
外壳需要是一个支撑typeset
,所以它必须是bash
or ksh
, not sh
(如所用script=True
默认情况下),这可以由ash
or dash
,缺少这个功能。
在给定的示例中,这是通过传递来实现的['ksh', '-c']
是 argv 数组的前两个参数。
-
typeset
需要在本地运行,因此它不能位于除第一个之外的 argv 位置script=True
。 (举个例子:subprocess.Popen(['''printf '%s\n' "$@"''', 'This is just literal data!', '$(touch /tmp/this-is-not-executed)'], shell=True)
仅评估printf '%s\n' "$@"
作为 shell 脚本;This is just literal data!
and $(touch /tmp/this-is-not-executed)
作为文字数据传递,因此没有名为/tmp/this-is-not-executed
被建造)。
在给定的示例中,这是由不使用 script=True
.
-
显式调用ksh -s
(or bash -s
,视情况而定)确保评估函数定义的 shell 与您的 shell 相匹配wrote这些函数反对,而不是传递给sh -c
,否则就会发生这种情况。
在给定的示例中,这是由ssh user@box ksh -s
在脚本里面。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)