这是我正在尝试做的,但我想改用 python:
test=$(perl -e 'print "test"')
[webalert@localhost scripts]$ echo $test
test
是否有 perl -e 的 python 等价物?谢谢。
最佳答案
$ test=$(python -c "print 'hello'")
$ echo $test
hello
(作为旁注...)
如果您想保留换行符,请在 echo
中使用引号:
$ test=$(python -c "for i in range(3): print 'hello'")
$ echo $test
hello hello hello
$ echo "$test"
hello
hello
hello
最后一个提示:
Perl 比 Python 更适合单行。我倾向于做这样的事情,而不是强制 python 成为一种它不是的语言:
$ test=$(python -c "
> import math
> import sys
>
> for x in sys.argv[1:]:
> print '2pi R of {}={}'.format(x,float(x)*2*math.pi)
> " 1 2.4 5 6.6)
$ echo "$test"
2pi R of 1=6.28318530718
2pi R of 2.4=15.0796447372
2pi R of 5=31.4159265359
2pi R of 6.6=41.4690230274
关于python - 将 python 输出保存到 shell 变量,类似于 perl -e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19692381/