Python Forum
[SOLVED] [Windows] Is this right way to run a CLI app?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] [Windows] Is this right way to run a CLI app?
#1
Question 
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
Reply
#2
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']
Reply
#3
Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] [Windows] Fails reading strings with accents Winfried 1 1,419 Apr-23-2023, 05:27 PM
Last Post: Larz60+
  [SOLVED] [Windows] Right way to prompt for directory? Winfried 4 3,040 Jan-17-2023, 09:28 PM
Last Post: markoberk
  [SOLVED] [Windows] Converting filename to UTF8? Winfried 5 4,537 Sep-06-2022, 10:47 PM
Last Post: snippsat
  SOLVED: best way to block (wait on) shell calls to multiple windows programs at once? ezdev 0 2,986 Dec-10-2017, 06:42 AM
Last Post: ezdev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020