1

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=$(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:

$ 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.

3 Answers3

1

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

print('nice dude
') 

which is not valid Python.

You can either add , end="") to the original print or figure out some other way to strip the trailing newline, or use e.g. triple quotes.

AKX
  • 152,115
  • 15
  • 115
  • 172
0

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
Aven Desta
  • 2,114
  • 12
  • 27
  • I can see what you're referring to but I actually did include the other quote `$ python3 -c "print('$VERSION')"` It prints like that in the error message because of some strange reason, similar to a carriage return. – Koyomi-Oniichan Feb 08 '21 at 15:31
0

I added and wrapped the python command with echo and it worked fine:

VERSION=$(echo $(python3 -c "print('nice dude')"))
$> echo $VERSION
nice dude
Rob Evans
  • 2,822
  • 1
  • 9
  • 15