Listing gcc error messages in python

Asked 1 months ago, Updated 1 months ago, 4 views

How do I put gcc error messages in a row-by-row list?
I want to use the gcc command file from the command line argument.

#coding:UTF-8

import subprocess
import sys
args=sys.argv
lines = [ ]

proc=subprocess.Popen(['gcc', 'Wall', 'Wextra', args[1]+'.c'.splitlines(), stderr=subprocess.PIPE)

lines=proc.stderr
print(lines)

The following error occurs when executing the above code

Traceback (most recent call last):
  File "test.py", line 8, in <module>
proc=subprocess.Popen(['gcc', 'Wall', 'Wextra', args[1]+'.c'.splitlines(), stderr=subprocess.PIPE)
AttributeError: 'list' object has no attribute' splitlines' 

For example, if the following error occurs:

 undec.c:In function 'main':
undec.c:8:2:error:'z' undeclared(first use in this function)
  z = 30;
  ^
undec.c:8:2:note:each undeclared identifier is reported only once for each function it appears in

I'd like to put it on the list as follows.

lines=["undec.c:Infunction'main':\n", "undec.c:8:2:error:'z' undeclared(first use in this function)/n", "z=30;\n", "^\n", "undec.c:8:2:note:each undeclared for occurrence\nearly notice

python python3 gcc

2022-09-30 11:24

2 Answers

import subprocess
import sys
args=sys.argv
lines = [ ]

proc=subprocess.run(['gcc', '-Wall', '-Wextra', args[1]+'.c', stderr=subprocess.PIPE)

lines=proc.stderr.decode('utf-8').splitlines(keepends=True)
print(lines)


2022-09-30 11:24

If you use subprocess.Popen(), you can also write with statement (context manager) as follows:

import subprocess
import sys

iflen(sys.argv)<2:
  print("None arguments." file=sys.stderr)
  sys.exit(1)

args=sys.argv
with subprocess.Popen([]
  'gcc', '-Wall', '-Wextra', args[1]+'.c'
], stderr=subprocess.PIPE, encoding='utf-8')asproc:
  lines=proc.stderr.readlines()

print(lines)


2022-09-30 11:24

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.