Home > Back-end >  Is it possible to get the contents of a variable with read_text() in Python script?
Is it possible to get the contents of a variable with read_text() in Python script?

Time:06-30

test.sh:

#!/bin/sh

hello="HELLO"
who="WORLD"
text="$hello $who"

test.py:

import pathlib

content = pathlib.Path('test.sh').read_text()
print(content)

I want to get variable $text in my script py

CodePudding user response:

You can use regular expressions, as content is a string variable:

import pathlib
import re

content = pathlib.Path('test.sh').read_text()
print(re.search('text="(. ?)"', content))

Output:

<re.Match object; span=(37, 55), match='text="$hello $who"'>

To get the exact text value, you can slice the string:

import pathlib
import re

content = pathlib.Path('test.sh').read_text()
v = re.search('text="(. ?)"', content)
print(v[0][6:-1])

Resulting in:

$hello $who

CodePudding user response:

You can add echo $text on your 'test.sh' file and then capture the output of the file by using:

import subprocess
subprocess.run(['./test.sh'], capture_output=True)
  • Related