从Python打开Developer Command Promt并编写命令

时间:2018-01-22 12:13:43

标签: python

我试图打开VS#2017开发人员命令提示符"从Python中,在cd ..之内写一些命令,然后运行一个exe。 但是它根本不允许我编写命令。 我试过了:

process = subprocess.Popen('C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Common7\\Tools\\VsDevCmd.bat',
                           shell=False, stdin=subprocess.PIPE, 
                           stdout=subprocess.PIPE, stderr=None)

process.stdin.write('1.txt'.encode(encoding='utf_8', errors='strict'));  
output = process.stdout.readlines()  
print(output)

当我自己打开开发人员命令promtpt时,它被定向到c:\>。 因此,我将c:\保存在名为1.txt的文本文件中,以了解它是否在Python中运行该命令。但是,在Python控制台中,我只收到欢迎文本:

[b'**********************************************************************\r\n',
 b'** Visual Studio 2017 Developer Command Prompt v15.5.2\r\n',
 b'** Copyright (c) 2017 Microsoft Corporation\r\n', 
 b'**********************************************************************\r\n']

1 个答案:

答案 0 :(得分:0)

问题在于VsDevCmd.bat关闭,然后才能与生成的子进程通信,因为我相信 您的方法有效,但如果您使用通信而不是直接将输入发送到stdin:

,则会更好
output = communicate('cd c: \n')[0]

Check the documentation on communicate

您可以使用通信和调用CMD来运行上面相同的代码:

process = subprocess.Popen('cmd',shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
output = process.communicate('dir\n')[0]
print output