You are assuming that Popen
finishes the process, but it doesn't; Popen
will merely start a process - and unless the compilation is extremely fast, it's quite likely that reddy.txt
will be empty when you try to read it.
With Python 3.5+ you want subprocess.run()
.
# Don't import *
from subprocess import run as s_run, PIPE, STDOUT
# Remove unused import
#import os
def compile():
# Use a context manager
with open("reddy.txt", "w+") as f:
# For style points, avoid shell=True
s_run(["gcc", "-c", "rahul.c "], stdout=f, stderr=STDOUT,
# Check that the compilation actually succeeds
check=True)
def run():
compile() # use the function we just defined instead of repeating youself
p2 = s_run(["r.exe"], stdout=PIPE, stderr=PIPE,
# Check that the process succeeds
check = True,
# Decode output from bytes() to str()
universal_newlines=True)
print(p2.stdout)
compile()
# Open file for reading, not writing!
with open("reddy.txt", "r") as f1:
first_char = f1.readline()
print(first_char)
(I adapted the run()
function along the same lines, though it's not being used in any of the code you posted.)
first_char
is misleadingly named; readline()
will read an entire line. If you want just the first byte, try
first_char = f1.read(1)
If you need to be compatible with older Python versions, try check_output
or check_call
instead of run
. If you are on 3.7+ you can use text=True
instead of the older and slightly misleadingly named universal_newlines=True
.
For more details about the changes I made, maybe see also this.