在Python中在新窗口中读取命令提示符输出。

huangapple go评论79阅读模式
英文:

Read command prompt output in new window in Python

问题

I referred to this Read Command Prompt output here. But I can't get it to work.

What I am trying to do is, I open a new command prompt window using subprocess.Popen and I want to run an exe file with some arguments. After I run that process, I want to capture the output or read the text in that command prompt.

When I say cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"', creationflags=CREATE_NEW_CONSOLE, shell=True, stdout=subprocess.PIPE) it won't run the process at all.

Please see this screenshot, I want to read the text in the command prompt.

在Python中在新窗口中读取命令提示符输出。

Just in case, here is the full code.

import os
import subprocess
from subprocess import Popen, CREATE_NEW_CONSOLE
import time
import ctypes, sys

#The command prompts must be opened as administrator. So need to run the python script with elevated permissions. Or else it won't work
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    #The program can only run with elevated admin privileges.

    #Get the directory where the file is residing.
    currentDirectory = os.path.dirname(os.path.abspath(__file__))
    coreServerFullPath = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer/bin\Debug")
    isExistCoreServer = os.path.exists(coreServerFullPath)

    echoServerFullPath = os.path.join(currentDirectory, "Echo\Server\EchoServer/bin\Debug")
    isExistEchoServer = os.path.exists(echoServerFullPath)

    #For now this is the MSBuild.exe path. Later we can get this MSBuild.exe as a standalone and change the path.
    msBuildPath = "C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
    pathOfCorecsProjFile = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer\CoreServer.csproj")
    pathOfEchocsProjFile = os.path.join(currentDirectory, "Echo\Server\EchoServer\EchoServer.csproj")

    def OpenServers():
        os.chdir(coreServerFullPath)
        cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"', creationflags=CREATE_NEW_CONSOLE)
        time.sleep(3)
        os.chdir(echoServerFullPath)
        #cmd.exe /K "EchoServer.exe -c -s"
        cmd1 = subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"', creationflags=CREATE_NEW_CONSOLE)

    if(not isExistCoreServer):
        if(os.path.isfile(pathOfCorecsProjFile)):
            os.chdir(msBuildPath)
            startCommand = "start cmd /c"
            command = "MSBuild.exe " + pathOfCorecsProjFile + " /t:build /p:configuration=Debug"
            cmd = subprocess.Popen(startCommand + command)

    if(not isExistEchoServer):
        if(os.path.isfile(pathOfEchocsProjFile)):
            os.chdir(msBuildPath)
            startCommand = "start cmd /c"
            command = "MSBuild.exe " + pathOfEchocsProjFile + " /t:build /p:configuration=Debug"
            os.system(startCommand + command)

    if(isExistCoreServer and isExistEchoServer):
        OpenServers()

else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
英文:

I referred to this Read Command Prompt output here. But I can't get it to work.

What I am trying to do is, I open a new command prompt window using subprocess.Popen and I want to run an exe file with some arguments. After I run that process, I want to capture the output or read the text in that command prompt.

When I say cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE,shell=True,stdout=subprocess.PIPE) it won't run the process at all.

import subprocess
from subprocess import Popen, CREATE_NEW_CONSOLE
def OpenServers():
os.chdir(coreServerFullPath)
cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
time.sleep(3)
os.chdir(echoServerFullPath)
#cmd.exe /K "EchoServer.exe -c -s"
cmd1=subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
#subprocess.Popen(['runas', '/user:Administrator', '"CoreServer.exe -c -s"'],creationflags=CREATE_NEW_CONSOLE
print("OUTPUT 1 "+cmd.stdout.readline())

Please see this screenshot, I want to read the text in the command prompt.

在Python中在新窗口中读取命令提示符输出。

Just in case, here is the full code.

import os
import subprocess
from subprocess import Popen, CREATE_NEW_CONSOLE
import time
import ctypes, sys
#The command prompts must be opened as administrator. So need to run the python script with elebvated permissions. Or else it won't work
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
#The program can only run with elevated admin previlages.
#Get the directory where the file is residing.
currentDirectory=os.path.dirname(os.path.abspath(__file__))
coreServerFullPath=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer/bin\Debug")
isExistCoreServer=os.path.exists(coreServerFullPath)
echoServerFullPath=os.path.join(currentDirectory,"Echo\Server\EchoServer/bin\Debug")
isExistEchoServer=os.path.exists(echoServerFullPath)
#For now this is the MSBuild.exe path. Later we can get this MSBuild.exe as a standalone and change the path.
msBuildPath="C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
pathOfCorecsProjFile=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer\CoreServer.csproj")
pathOfEchocsProjFile=os.path.join(currentDirectory,"Echo\Server\EchoServer\EchoServer.csproj")
def OpenServers():
os.chdir(coreServerFullPath)
cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
time.sleep(3)
os.chdir(echoServerFullPath)
#cmd.exe /K "EchoServer.exe -c -s"
cmd1=subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
#subprocess.Popen(['runas', '/user:Administrator', '"CoreServer.exe -c -s"'],creationflags=CREATE_NEW_CONSOLE
if(not isExistCoreServer):
if(os.path.isfile(pathOfCorecsProjFile)):
os.chdir(msBuildPath)
startCommand="start cmd /c"
command="MSBuild.exe "+pathOfCorecsProjFile+" /t:build /p:configuration=Debug"
#os.system(startCommand+command)
cmd=subprocess.Popen(startCommand+command)
if(not isExistEchoServer):
if(os.path.isfile(pathOfEchocsProjFile)):
os.chdir(msBuildPath)
startCommand="start cmd /c"
command="MSBuild.exe "+pathOfEchocsProjFile+" /t:build /p:configuration=Debug"
os.system(startCommand+command)
if(isExistCoreServer and isExistEchoServer):
OpenServers()
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

答案1

得分: 0

以下是翻译好的内容:

也许这就是您在寻找的:https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output

那里的答案非常详尽,我建议完整阅读。 总结如下:

Python 3.5+

如果您正在使用Python 3.5+,那么您可能想要使用subprocess中的run方法

import subprocess

result = subprocess.run(['CoreServer.exe', '-c', '-s'], stdout=subprocess.PIPE)
print(result.stdout)

Python 3-3.4

如果您正在使用Python 3-3.4,那么您将想要使用subprocess中的check_output方法

import subprocess

output = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
print(output)
英文:

Perhaps this might be what you are looking for: https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output

The answer there is very in depth, and I would recommend reading in full. To summarize:

Python 3.5+

If you are using Python 3.5+, then likely you want to use the run method in subprocess

import subprocess

result = subprocess.run(['CoreServer.exe', '-c', '-s'], stdout=subprocess.PIPE)
print(result.stdout)

Python 3-3.4

If you are using Python 3-3.4, then you will want to use the check_output method in subprocess

import subprocess

output = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
print(output)

huangapple
  • 本文由 发表于 2023年2月24日 12:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定