I would like to be able to start, stop and get the console output of another python program. I don't want to run it within the current program, I want them to run as two separate instances.
Both of the files are in the same directory.
I have seen guides on how to get the console output of another python program, as well as how to start and stop it, but I haven't been able to find a guide on both.
I should also note that the file I want the output from is a .pyw file.
Thanks.
EDIT: Not a duplicate, it is not that simple...
EDIT2:
Here is my attempt
main.py
import subprocess
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# continue with your code then terminate the child
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line)
p.wait()
sub.py
import time
for i in range(100):
print(i)
time.sleep(1)
It sort of works, but it prints it like
b'0\r\n' b'1\r\n' b'2\r\n' b'3\r\n' b'4\r\n'
EDIT3:
import subprocess
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
Is this the best way?
However, I am still having issues. I want to run the program completely separately, and so I should be able to run other code in the main.py
program at the same time, but that is not working.
import subprocess
import time
def get_output():
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
def print_stuff():
for i in range(100):
print("." + str(i))
time.sleep(1)
if __name__ == "__main__":
get_output()
print_stuff()
import time
def main():
for i in range(100):
print(i)
time.sleep(1)
if __name__ == "__main__":
main()
EDIT4: Here is my attempt at running them both at the same time
import subprocess
import asyncio
async def get_output():
p = subprocess.Popen(['python', 'sub.py', 'watch', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
async def print_stuff():
for i in range(100):
print("." + str(i))
await asyncio.sleep(1)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
print_stuff(),
get_output()
))
loop.close()
import asyncio
async def main():
for i in range(100):
print(i)
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
The expected output is
.0 0 .1 1 .2 2 ...
But the output is
.0 0 1 2 3 4 5 ...
EDIT5:
I believe the issue is that subprocess.Popen
holds the program, so I think I need to use asyncio.create_subprocess_exec
m but I can't figure out exactly how to get that to work.