简体   繁体   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. 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.

In this case, we have VERSION set to "nice dude"在这种情况下,我们将VERSION设置为"nice dude"

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

And printing the variable alone seems to work单独打印变量似乎有效

$ echo $VERSION

>>> nice dude

But when I implement this value with anything else, Python for example:但是当我用其他任何东西实现这个值时,例如 Python:

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

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

Or when I print it again with some concatenation:或者当我用一些连接再次打印它时:

$ echo $VERSION hehe

>>>  hehedude

I'm not sure what's happening but it seems to be some sort of carriage return when printing an output produced by python python3.9.1 .我不确定发生了什么,但在打印由 python python3.9.1生成的 output 时,它似乎是某种回车。

After

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

the VERSION shell variable will contain a trailing newline, so interpolating it into Python code with python3 -c "print('$VERSION')" will result in VERSION shell 变量将包含一个尾随换行符,因此使用python3 -c "print('$VERSION')"将其插入 Python 代码将导致

print('nice dude
') 

which is not valid Python.这是无效的 Python。

You can either add , end="") to the original print or figure out some other way to strip the trailing newline, or use eg triple quotes.您可以在原始打印中添加, end="")或找出其他方法来去除尾随换行符,或者使用例如三引号。

I couln't replicate your result so I tried to look for what might have caused your error.我无法复制您的结果,因此我尝试查找可能导致您的错误的原因。

>> "This is a test

Then I got the same error.然后我得到了同样的错误。

It seems your error is that there is un-closed quote at the end.看来您的错误是最后有未关闭的报价。

Look here for more. 在这里查看更多信息。

So you're probably forgetting closing an opened quote somewhere at the end.因此,您可能忘记在最后某处关闭已打开的报价。 Here is what possibly might I happened这是我可能发生的事情

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

I added and wrapped the python command with echo and it worked fine:我用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