簡體   English   中英

使用Python的函數返回值為shell變量賦值

[英]assigning value to shell variable using a function return value from Python

我有一個Python函數,fooPy()返回一些值。 (int / double或string)

我想使用此值並將其分配給shell腳本。 例如,以下是python函數:

def fooPy():
    return "some string" 
    #return 10  .. alternatively, it can be an int

fooPy()

在shell腳本中,我嘗試了以下內容,但它們都不起作用。

fooShell = python fooPy.py
#fooShell = $(python fooPy.py)
#fooShell = echo "$(python fooPy.py)"

您可以在Python中打印您的值,如下所示:

print fooPy()

並在您的shell腳本中:

fooShell=$(python fooPy.py)

請確保不要在shell腳本中的=周圍留出空格。

在Python代碼中,您需要打印結果。

import sys
def fooPy():
    return 10 # or whatever

if __name__ == '__main__':
    sys.stdout.write("%s\n", fooPy())

然后在shell中,你可以這樣做:

fooShell=$(python fooPy.py) # note no space around the '='

請注意,我在Python代碼中添加了if __name__ == '__main__'檢查,以確保僅在從命令行運行程序時才進行打印,而不是從Python解釋器導入程序時。

我也使用sys.stdout.write()而不是print ,因為

  • print在Python 2和Python 3中有不同的行為,
  • 在“真實程序”中,應該使用sys.stdout.write()而不是print :-)

如果你想要Python sys.exit語句中的值,它將在shell特殊變量$?

$ var=$(foo.py)
$ returnval=$?
$ echo $var
Some string
$ echo returnval
10

你應該print fooPy返回的值。 shell替換從stdout讀取。 print fooPy()替換程序的最后一行,然后使用你提到的第二個shell管道。 它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM