subprocess.Popen in different console

前端 未结 3 775
轮回少年
轮回少年 2020-12-01 10:19

I hope this is not a duplicate.

I\'m trying to use subprocess.Popen() to open a script in a separate console. I\'ve tried setting the shell=True

3条回答
  •  醉梦人生
    2020-12-01 11:12

    from subprocess import *
    
    c = 'dir' #Windows
    
    handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
    print handle.stdout.read()
    handle.flush()
    

    If you don't use shell=True you'll have to supply Popen() with a list instead of a command string, example:

    c = ['ls', '-l'] #Linux
    

    and then open it without shell.

    handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
    print handle.stdout.read()
    handle.flush()
    

    This is the most manual and flexible way you can call a subprocess from Python. If you just want the output, go for:

    from subproccess import check_output
    print check_output('dir')
    

    To open a new console GUI window and execute X:

    import os
    os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)
    

提交回复
热议问题