Home > Blockchain >  unable to read makefile using python
unable to read makefile using python

Time:01-20

I am trying to read the contents of the Makefile using python.

Makefile

# Dev Makefile

SHELL := /bin/bash
platform_ns ?= abc
app_namespace ?= xyz

wftmpl = wftmpl.yaml
wftmpl_name ?= abc.yaml
service_account ?= dev_account
br_local_port = 8000
tr_local_port = 8001
storage_root_path ?= some_location

I used the following code to read the file in python file expocting all the files in the same directory.

python_script.py

with open("Makefile", "r") as file:
    while (line := file.readline().rstrip()):
        print(line)

Expected output

# Dev Makefile

SHELL := /bin/bash
platform_ns ?= abc
app_namespace ?= xyz

wftmpl = wftmpl.yaml
wftmpl_name ?= abc.yaml
service_account ?= dev_account
br_local_port = 8000
tr_local_port = 8001
storage_root_path ?= some_location

Current output

# Dev Makefile

I need to print all the content of the Makefile using python

CodePudding user response:

The problem is that the while condition is the line after calling rstrip(). If the line is blank, this will be an empty string, and this is falsey, so the loop ends.

You should test the line before stripping it.

while (line := file.readline()):
    print(line.rstrip())

or more simply:

for line in file:
    print(line.rstrip())

CodePudding user response:

Try :

with open("Makefile", "r") as file:
    for line in file.read().splitlines():
        print(line)
  • Related