简体   繁体   中英

How to communicate with command line program using python?

import subprocess
import sys

proc = subprocess.Popen(["program.exe"], stdin=subprocess.PIPE) #the cmd program opens
proc.communicate(input="filename.txt") #here the filename should be entered (runs)
#then the program asks to enter a number:
proc.communicate(input="1") #(the cmd stops here and nothing is passed)
proc.communicate(input="2") # (same not passing anything)

how do i pass and communicate with the cmd using python.

Thanks. (using windows platform)

The docs on communicate() explain this:

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

communicate() blocks once the input has been sent until the program finishes executing. In your example, the program waits for more input after you send "1" , but Python waits for it to exit before it gets to the next line, meaning the whole thing deadlocks.

If you want to read and write a lot interchangeably, make pipes to stdin / stdout and write/read to/from them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM