简体   繁体   English

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

[英]save python output to shell variable, similar to perl -e

Here is what I am trying to do but I want to use python instead: 这是我想做的事情,但我想改用python:

test=$(perl -e 'print "test"')
[webalert@localhost scripts]$ echo $test
test

Is there a python equivalent for perl -e ? 是否有等效于perl -e的python? Thx. 谢谢。

$ test=$(python -c "print 'hello'")
$ echo $test
hello

(as a side note...) If you want to preserve newlines, use quotes in the echo : (作为旁注...)如果要保留换行符,请在echo使用引号:

$ test=$(python -c "for i in range(3): print 'hello'")
$ echo $test
hello hello hello
$ echo "$test"
hello
hello
hello

One final tip: 最后一点提示:

Perl lends itself to one liners a bit better than Python does. Perl比Python更适合自己。 I tend to do something like this rather than coerce python into being a language it is not: 我倾向于做这样的事情,而不是强迫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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM