简体   繁体   中英

Read the value from a file with Python

My file contents:

NAME="A"
VERSION="20190515231057-816a"
VERSION_ID="2.0"
BUILD_ID="16a438d965923ab62804cea4ba00"
BUILDER_NAME="v1.0"
BUILDER_VERSION="v1.0"

I need to read any data value, for example BUILDER_VERSION is value (v1.0). I tried following code however it gives error due to special characters. How can I fix the problem or please suggest different commands?

build_value = subprocess.check_output("sed -ne 's/BUILDER_VERSION=\([^]*\).*/\1/p' < /etc/os-release", shell=True)

In python you could avoid using subprocess for such simple case. You can read file directly with open() or accept "standard input" from sys.stdin (you would need to import sys before that).

import sys
for line in sys.stdin:
    if line.startswith('BUILDER_VERSION='):
          value = line.split('=', 1)
          print(value[1] if value or 'No version')
          break
 else:
      print('version is not found')

you would use it similar to sed: cat /etc/os-release|python this_script.py

if want to extract number, you could use same regex:

import re
version_extractor = re.compile(r'BUILDER_VERSION=([^^]*)')

with open('/etc/os-release', 'r') as file:
   for line in file:
       match = version_extractor.match(line)
       if match:
           print(match.groups()[0])

You could try something like:

with open(FILE_NAME, 'r') as file:
    parsed = file.read().split('\n')
    for item in parsed:
        if VAR_NAME in item:
            print(item)

That would print the entire line of the file containing the variable name. You could also save the line as a string literal and break it down further with slicing, splitting, regex, etc.

I'm sure there are cleaner ways to do that, though, so I would check out some Python documentation on reading files!

Replace sed command with following:

sed -n 's/^BUILDER_VERSION*= *//p' < /etc/os-release

you can replace BUILDER_VERSION with required pattern

I Changed sed -n 's/^BUILDER_VERSION*= *//p' < /etc/os-release command. Now fine working. Also I added .replace('"', '') to the end of the subprocess command for v1.0. Thank you everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM