Python Forum

Full Version: [SOLVED] [Windows] Is this right way to run a CLI app?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

From Python, I need to run a couple of command-line apps in Windows.

Is this the right way to do it, including how to tell if the apps ran successfully?

Thank you.

import subprocess
import shlex

URL = r"http://www.acme.com"
my_command = fr"C:\acme.exe {URL}"
my_cmd = shlex.split(my_command)

p = subprocess.Popen(my_cmd, stdout=subprocess.PIPE, text=True)
while (line := p.stdout.readline()) != "":
	pass
print(f"End of output.  Return code: {p.wait()}")
#TODO handle success/error
Example like this,use run() in all cases it handle.

subprocess doc Wrote:The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle.
For more advanced use cases, the underlying Popen interface can be used directly.
import subprocess

my_command = 'ping google.com'
my_cmd = shlex.split(my_command)
output = subprocess.run(my_cmd, encoding='utf-8', capture_output=True)
print(output.stdout)
Output:
Pinging google.com [142.250.74.110] with 32 bytes of data: Reply from 142.250.74.110: bytes=32 time=32ms TTL=113 Reply from 142.250.74.110: bytes=32 time=46ms TTL=113 Reply from 142.250.74.110: bytes=32 time=39ms TTL=113 Reply from 142.250.74.110: bytes=32 time=45ms TTL=113 Ping statistics for 142.250.74.110: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 32ms, Maximum = 46ms, Average = 40ms
You most test your code better.
import subprocess
import shlex

URL = r"http://www.acme.com"
my_command = fr"C:\acme.exe {URL}"
my_cmd = shlex.split(my_command)
print(my_cmd)
Output:
['C:acme.exe', 'http://www.acme.com']
C:acme.exe will never work it should be C:\acme.exe or C:/acme.exe
Fix.
import subprocess
import shlex

URL = "http://www.acme.com"
my_command = f"C:/acme.exe {URL}"
my_cmd = shlex.split(my_command)
print(my_cmd)
Output:
['C:/acme.exe', 'http://www.acme.com']
Thank you.