Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - Displaying live cmd results from Subprocess Popen

I'm trying to write a code that will make changes to an external Python venv. I'm using the Subprocess module to connect to cmd to do so.

But I faced a problem. The program is finishing running before the cmd code actually finishes the job.

Is there anyway to sync it? And maybe even display live cmd results?

The code:

import subprocess
cmds = [f"""cd {venv_path}""",
        "activate",
        "timeout 5", #for example
        "exit"]

shell_instance = subprocess.Popen('cmd.exe',
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                        universal_newlines=True,
                       shell=True)

for cmd in cmds:
    shell_instance.stdin.write(cmd+"
")


shell_instance.stdin.close()

for line in shell_instance.stdout:
    print(line.strip())

print(shell_instance.returncode)

The results:

Microsoft Windows [Version 10.0....]
(c) 2020 Microsoft Corporation. All rights reserved.

(venv) C:Usersdani2PycharmProjectsautoIISconfig>cd C:Usersdani2PycharmProjectsautoIISconfigvenvScripts

(venv) C:Usersdani2PycharmProjectsautoIISconfigvenvScripts>activate

(venv) C:Usersdani2PycharmProjectsautoIISconfigvenvScripts>timeout 5

(venv) C:Usersdani2PycharmProjectsautoIISconfigvenvScripts>exit
None

Process finished with exit code 0

The code does not wait the 5 seconds.

Thank you for your help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...