Python Forum
How to run a program with python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to run a program with python
#1
Hello Members,

I have a need to write a python program which calls a specific program that require some parameters while and after calling. The problem is that this program is kind a interactive problem, like linux "nmon". Lets consider the program i'm trying to call is "nmon". Is it possible to call it and pass some parameters? For example: the script calls the program, after a while pass the parameter "m" and after some time pass the parameter "q".

Best Regards,
Rafael
Reply
#2
Can use subprocess for this.
Example with call of ping from command line ping -n 4 google.com
import subprocess

output = subprocess.run(['ping', '-n', '4', 'google.com'], encoding='utf-8', capture_output=True)
print(output.stdout)
Output:
Pinging google.com [2a00:1450:400f:80b::200e] with 32 bytes of data: Reply from 2a00:1450:400f:80b::200e: time=42ms Reply from 2a00:1450:400f:80b::200e: time=33ms Reply from 2a00:1450:400f:80b::200e: time=46ms Reply from 2a00:1450:400f:80b::200e: time=50ms Ping statistics for 2a00:1450:400f:80b::200e: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 33ms, Maximum = 50ms, Average = 42ms
Reply
#3
Hello snippsat,

I've done tests with subprocess already. In your example, when the ping program finishes the process the program/call ends. The "nmon" for example, the program continues running and you must type a "control-c" or type the letter "d" for finishing the program. The program i'm trying to call is a SAP program ("dpmon") that behaves like nmon. If you
want to test with ping program to emulate the behaviour, we should call it with the "-t" parameter. So, in this case, it'll be necessary to enter a "control-c" to stop the ping response.

Thank you!
Rafael M.
Reply
#4
Hello,

I've found a solution. The behaviour I was expecting was accomplish with something like that:


import time
from subprocess import Popen, PIPE

def __run(cmd, show_output=True):

    proc = Popen(cmd, stdin=PIPE, shell=True)
    proc.stdin.write('m')
    proc.stdin.flush()
    time.sleep(3)
    proc.stdin.write('l')
    proc.stdin.flush()
    time.sleep(3)
    proc.communicate('q')

__run("nmon")
Thank you all,
Rafael
Reply
#5
Added code tag in your post,look at BBcode
Thanks for reporting back with a solution.
Reply


Forum Jump:

User Panel Messages

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