How to use creationflags=CREATE_NO_WINDOW with subprocess.run?

时间:2019-04-08 13:32:40

标签: python-3.x subprocess cygwin

I'm trying to create a simple python/tkinter UI to run cygwin commands from Windows.

To avoid getting a command window, I'm starting my python script with pythonw.exe.

Here's the code that runs the cygwin command:

def exec_ls():
    clear_log(log)
    print_log(log, "*** Running ls -lsa ***\n")
    s = subprocess.run(
        ["C:/cygwin/bin/ksh.exe", "-c", ". /etc/profile; ls -1 c:/test"],
        stdout=PIPE,
        stderr=STDOUT,
    )
    print_log(log, s.stdout)
    print_log(log, "\n*** END ***")

This runs successfully, but when exec_ls() is invoked, an empty command window flashes.

To remove the occurrence of this window, I tried to use creationflags as follows:

def exec_ls():
    clear_log(log)
    print_log(log, "*** Running ls -lsa ***\n")
    s = subprocess.run(
        ["C:/cygwin/bin/ksh.exe", "-c", ". /etc/profile; ls -1 c:/test"],
        stdout=PIPE,
        stderr=STDOUT,
        creationflags=CREATE_NO_WINDOW,
    )
    print_log(log, s.stdout)
    print_log(log, "\n*** END ***")

But then I don't get the command window, but the command doesn't run either (no output).

What did I do wrong?

Best regards

1 个答案:

答案 0 :(得分:0)

我发现了问题:CREATE_NO_WINDOW的导入丢失了,但是由于没有命令窗口,所以我看不到相应的错误消息。

import subprocess
from subprocess import PIPE, STDOUT, CREATE_NO_WINDOW

我是通过在命令窗口而不是从我创建的快捷方式中使用pythonw.exe运行脚本来找到它的。