Ras
Ras

Reputation: 547

Seems like subprocess.Popen is not releasing the lock

I am trying to execute a batch script through python and seems like subprocess.Popen is executing the command and it's getting stuck there on terminal and not printing any output though copy completed. Can you help on this.

ps_copy_command = "call copyfiles.cmd"
process=subprocess.Popen(["cmd", "/C", ps_copy_command, password], stdout=subprocess.PIPE, stderr=subprocess.PIPE);
    process.wait()
    print("\tCopy completed ")
    output = process.stdout.read()
    print (output)

Upvotes: 0

Views: 650

Answers (2)

Ras
Ras

Reputation: 547

I am using subprocess.run to address this.

process=subprocess.run(["cmd", "/C", ps_copy_command, password], stdout=subprocess.PIPE);
    print(process.returncode)
    print(process.stdout)

Upvotes: 0

Sergio GM
Sergio GM

Reputation: 78

If the code is stuked in output = process.stdout.read(), something similar happened to me some time ago. The problem is that process.stdout.read() wont return something until stdout has something in it. Example:

Imagine your batch script is doing some task that takes 10 seconds and then print 'Done!'

python is going to wait until 'Done!' returned by the script.

They way i solved this problems is by adding Threads. One thread is reading the stdout and the other is waiting n seconds, then i join the waiting thread and if the stdout thread has something in it, i print it

import time
import threading

def wait_thread():
    seconds = 0
    while seconds < 2:
        time.sleep(1)
        seconds += 1
    return True

def stdout_thread():
    global output
    output = process.stdout.read()


output=None
t1 = threading.Thread(target=wait_thread)
t2 = threading.Thread(target=stdout_thread)

t1.start()
t2.start()

t1.join()     # wait until waiting_thread is end  

if output:
    print(output)
else:
    print("No output")

Upvotes: 1

Related Questions