将python输出保存到shell变量,类似于perl -e

rad*_*tek 1 python shell

这是我想要做的但我想使用python:

test=$(perl -e 'print "test"')
[webalert@localhost scripts]$ echo $test
test
Run Code Online (Sandbox Code Playgroud)

Perl -e有一个python等价物吗?谢谢.

daw*_*awg 5

$ test=$(python -c "print 'hello'")
$ echo $test
hello
Run Code Online (Sandbox Code Playgroud)

(作为旁注...)如果要保留换行符,请在以下位置使用引号echo:

$ test=$(python -c "for i in range(3): print 'hello'")
$ echo $test
hello hello hello
$ echo "$test"
hello
hello
hello
Run Code Online (Sandbox Code Playgroud)

最后一个提示:

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
Run Code Online (Sandbox Code Playgroud)