Python Popen writing command prompt output to logfile
Question:
Firstly I am running this Python script on Windows.
I am trying to open a new command prompt window every time and want to execute a .exe with some arguments. After I execute, I want to copy the command prompt output to a log file. I created a log file at the location say "log.log". When I run the script, it doesn’t seem to write the contents to the log file at all.
The coreServerFullPath is like C:UsersnandukDesktopSourceCodeCoreCoreServerServerCoreServerbinDebug
And here in this location I created a blank text document and named it to log.log
def OpenCoreServer():
os.chdir(coreServerFullPath)
#logging.basicConfig(filename="log.log", level=logging.INFO)
logging.info('your text goes here') #I see this line in the log.
result = subprocess.Popen('start cmd /k "CoreServer.exe -c -s" >> log.log 2>&1', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
time.sleep(4)
print("ABCD")
with open('log.log', 'r') as logg:
print(logg.read())
Answers:
You might be able to get away with something like
import subprocess
import time
os.chdir(coreServerFullPath)
with open("log.log", "ab") as log:
proc = subprocess.Popen("CoreServer.exe", stdout=log, stderr=log)
while proc.poll() is None:
# Do something while the process is running
time.sleep(1)
print("CoreServer exited with code", proc.returncode)
Firstly I am running this Python script on Windows.
I am trying to open a new command prompt window every time and want to execute a .exe with some arguments. After I execute, I want to copy the command prompt output to a log file. I created a log file at the location say "log.log". When I run the script, it doesn’t seem to write the contents to the log file at all.
The coreServerFullPath is like C:UsersnandukDesktopSourceCodeCoreCoreServerServerCoreServerbinDebug
And here in this location I created a blank text document and named it to log.log
def OpenCoreServer():
os.chdir(coreServerFullPath)
#logging.basicConfig(filename="log.log", level=logging.INFO)
logging.info('your text goes here') #I see this line in the log.
result = subprocess.Popen('start cmd /k "CoreServer.exe -c -s" >> log.log 2>&1', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
time.sleep(4)
print("ABCD")
with open('log.log', 'r') as logg:
print(logg.read())
You might be able to get away with something like
import subprocess
import time
os.chdir(coreServerFullPath)
with open("log.log", "ab") as log:
proc = subprocess.Popen("CoreServer.exe", stdout=log, stderr=log)
while proc.poll() is None:
# Do something while the process is running
time.sleep(1)
print("CoreServer exited with code", proc.returncode)