簡體   English   中英

如何將 python 腳本的 output 重定向到 bash 變量?

[英]How to redirect output of python script to bash variable?

When redirecting the output of a python script, when echoing the output it seems to work, but when I actually use it with another object, it breaks and cuts off everything after it.

在這種情況下,我們將VERSION設置為"nice dude"

VERSION=$(python3 -c "print('nice dude')")

單獨打印變量似乎有效

$ echo $VERSION

>>> nice dude

但是當我用其他任何東西實現這個值時,例如 Python:

$ python3 -c "print('$VERSION')"

>>>   File "<string>", line 1
>>>     print('nice dude
>>>                     ^
>>> SyntaxError: EOL while scanning string literal

或者當我用一些連接再次打印它時:

$ echo $VERSION hehe

>>>  hehedude

我不確定發生了什么,但在打印由 python python3.9.1生成的 output 時,它似乎是某種回車。

VERSION=$(python3 -c "print('nice dude')")

VERSION shell 變量將包含一個尾隨換行符,因此使用python3 -c "print('$VERSION')"將其插入 Python 代碼將導致

print('nice dude
') 

這是無效的 Python。

您可以在原始打印中添加, end="")或找出其他方法來去除尾隨換行符,或者使用例如三引號。

我無法復制您的結果,因此我嘗試查找可能導致您的錯誤的原因。

>> "This is a test

然后我得到了同樣的錯誤。

看來您的錯誤是最后有未關閉的報價。

在這里查看更多信息。

因此,您可能忘記在最后某處關閉已打開的報價。 這是我可能發生的事情

VERSION=$(python3 -c "print('nice dude')") 
python3 -c "print('$VERSION)"
  File "<string>", line 1
    print('nice dude)
                    ^
SyntaxError: EOL while scanning string literal

我用echo添加並包裝了python命令,它運行良好:

VERSION=$(echo $(python3 -c "print('nice dude')"))
$> echo $VERSION
nice dude

暫無
暫無

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

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