简体   繁体   English

是否可以在 Python 脚本中使用 read_text() 获取变量的内容?

[英]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.

相关问题 Python read_text() 添加额外的字符串 - Python read_text() adding extra strings 达克斯袋read_text()行顺序 - Dask Bag read_text() line order Pathlib read_text 作为字符串文字 - Pathlib read_text as a string literal Weasyprint 在调用 write_pdf 时获得未定义的属性:“AttributeError: &#39;PosixPath&#39; 对象没有属性 &#39;read_text&#39;” - Weasyprint get undefined property at invoking write_pdf: "AttributeError: 'PosixPath' object has no attribute 'read_text'" 如何让 python 只读取文本文件的内容一次 - How to get python to only read the contents of a text file once 是否可以使用groovy脚本从文本文件读取python函数输出? - Is it possible to read python function output from text file with groovy script? pathlib read_text() 方法如何在 Windows 10 Enterprise 上正确显示 German Umlaute? - How can pathlib read_text() method display German Umlaute correctly on Windows 10 Enterprise? AttributeError: 'PosixPath' object 在构建 heroku 应用程序时没有属性 'read_text' - AttributeError: 'PosixPath' object has no attribute 'read_text' while building heroku app 将文本文件的内容读入 Python 中的字典 - Read contents of a text file into a Dictionary in Python Python:在脚本中保护敏感变量内容 - Python: securing sensitive variable contents within a script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM