pythonbashshell

How to define a Bash variable from Python EOF


I'm relatively new to Bash and unable to explain my problem in the title. I've done a lot of googling and I guess that's the title I came up with.

I want to be able to use Python EOF and define a Bash variable in the EOF (if possible) and call it after.

File test.txt

everything - literally the string everything

And I'm opening this file and getting contents with

File test.sh

#!/bin/bash
CMD=$(cat <<EOF

with open('text.txt', 'r') as f:
    for line in f.readlines():
          pass

print(f"WOW text has {line}")

EOF
)

python3 -c "$CMD"

Output:

WOW text has everything

I want to be able to share a variable by defining it in my CMD (I don't know what it's called) and echo it in Bash after it's done;

#!/bin/bash
CMD=$(cat <<EOF

with open('text.txt', 'r') as f:
    for line in f.readlines():
          pass

print(f"WOW text has {line}")
$var = line - somehow define a Bash variable in Python EOF
EOF
)

python3 -c "$CMD"
echo $var - output this

So then the new output (of what I want) is:

WOW text has everything
everything

Solution

  • I want to be able to share a variable by defining it in my CMD

    That is not possible.

    I want to

    Write a Bash builtin or path Bash with a modification that creates a shared memory region and introduces a new special variable that uses that shared memory region to store and fetch the value of the variable.

    Use the shared memory region from python to store the value of the variable.

    You could also go three steps further, and just straight introduce a Bash loadable module with interface to Python with communication via a local socket or similar, similar to vim Python library.


    You can:

    You may want to research "processes" - what they are, what do they share and what they don't share, and what are the methods of communication between processes.