[英]Is it possible to get the contents of a variable with read_text() in Python script?
test.sh:测试.sh:
#!/bin/sh
hello="HELLO"
who="WORLD"
text="$hello $who"
test.py:测试.py:
import pathlib
content = pathlib.Path('test.sh').read_text()
print(content)
I want to get "HELLO WORLD" in my script py我想在我的脚本 py 中获得“HELLO WORLD”
You can add echo $text
on your 'test.sh' file and then capture the output of the file by using:您可以在“test.sh”文件中添加
echo $text
,然后使用以下命令捕获文件的 output:
import subprocess
subprocess.run(['./test.sh'], capture_output=True)
You can use regular expressions, as content
is a string variable:您可以使用正则表达式,因为
content
是一个字符串变量:
import pathlib
import re
content = pathlib.Path('test.sh').read_text()
print(re.search('text="(.+?)"', content))
Output: Output:
<re.Match object; span=(37, 55), match='text="$hello $who"'>
To get the exact text
value, you can slice the string:要获得确切的
text
值,您可以对字符串进行切片:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.