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

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

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.

  1. import os
  2. import subprocess
  3. from subprocess import Popen, CREATE_NEW_CONSOLE
  4. import time
  5. import ctypes, sys
  6. #The command prompts must be opened as administrator. So need to run the python script with elevated permissions. Or else it won't work
  7. def is_admin():
  8. try:
  9. return ctypes.windll.shell32.IsUserAnAdmin()
  10. except:
  11. return False
  12. if is_admin():
  13. #The program can only run with elevated admin privileges.
  14. #Get the directory where the file is residing.
  15. currentDirectory = os.path.dirname(os.path.abspath(__file__))
  16. coreServerFullPath = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer/bin\Debug")
  17. isExistCoreServer = os.path.exists(coreServerFullPath)
  18. echoServerFullPath = os.path.join(currentDirectory, "Echo\Server\EchoServer/bin\Debug")
  19. isExistEchoServer = os.path.exists(echoServerFullPath)
  20. #For now this is the MSBuild.exe path. Later we can get this MSBuild.exe as a standalone and change the path.
  21. msBuildPath = "C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
  22. pathOfCorecsProjFile = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer\CoreServer.csproj")
  23. pathOfEchocsProjFile = os.path.join(currentDirectory, "Echo\Server\EchoServer\EchoServer.csproj")
  24. def OpenServers():
  25. os.chdir(coreServerFullPath)
  26. cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"', creationflags=CREATE_NEW_CONSOLE)
  27. time.sleep(3)
  28. os.chdir(echoServerFullPath)
  29. #cmd.exe /K "EchoServer.exe -c -s"
  30. cmd1 = subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"', creationflags=CREATE_NEW_CONSOLE)
  31. if(not isExistCoreServer):
  32. if(os.path.isfile(pathOfCorecsProjFile)):
  33. os.chdir(msBuildPath)
  34. startCommand = "start cmd /c"
  35. command = "MSBuild.exe " + pathOfCorecsProjFile + " /t:build /p:configuration=Debug"
  36. cmd = subprocess.Popen(startCommand + command)
  37. if(not isExistEchoServer):
  38. if(os.path.isfile(pathOfEchocsProjFile)):
  39. os.chdir(msBuildPath)
  40. startCommand = "start cmd /c"
  41. command = "MSBuild.exe " + pathOfEchocsProjFile + " /t:build /p:configuration=Debug"
  42. os.system(startCommand + command)
  43. if(isExistCoreServer and isExistEchoServer):
  44. OpenServers()
  45. else:
  46. # Re-run the program with admin rights
  47. 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.

  1. import subprocess
  2. from subprocess import Popen, CREATE_NEW_CONSOLE
  3. def OpenServers():
  4. os.chdir(coreServerFullPath)
  5. cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
  6. time.sleep(3)
  7. os.chdir(echoServerFullPath)
  8. #cmd.exe /K "EchoServer.exe -c -s"
  9. cmd1=subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
  10. #subprocess.Popen(['runas', '/user:Administrator', '"CoreServer.exe -c -s"'],creationflags=CREATE_NEW_CONSOLE
  11. 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.

  1. import os
  2. import subprocess
  3. from subprocess import Popen, CREATE_NEW_CONSOLE
  4. import time
  5. import ctypes, sys
  6. #The command prompts must be opened as administrator. So need to run the python script with elebvated permissions. Or else it won't work
  7. def is_admin():
  8. try:
  9. return ctypes.windll.shell32.IsUserAnAdmin()
  10. except:
  11. return False
  12. if is_admin():
  13. #The program can only run with elevated admin previlages.
  14. #Get the directory where the file is residing.
  15. currentDirectory=os.path.dirname(os.path.abspath(__file__))
  16. coreServerFullPath=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer/bin\Debug")
  17. isExistCoreServer=os.path.exists(coreServerFullPath)
  18. echoServerFullPath=os.path.join(currentDirectory,"Echo\Server\EchoServer/bin\Debug")
  19. isExistEchoServer=os.path.exists(echoServerFullPath)
  20. #For now this is the MSBuild.exe path. Later we can get this MSBuild.exe as a standalone and change the path.
  21. msBuildPath="C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
  22. pathOfCorecsProjFile=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer\CoreServer.csproj")
  23. pathOfEchocsProjFile=os.path.join(currentDirectory,"Echo\Server\EchoServer\EchoServer.csproj")
  24. def OpenServers():
  25. os.chdir(coreServerFullPath)
  26. cmd = subprocess.Popen('cmd.exe /K "CoreServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
  27. time.sleep(3)
  28. os.chdir(echoServerFullPath)
  29. #cmd.exe /K "EchoServer.exe -c -s"
  30. cmd1=subprocess.Popen('cmd.exe /K "EchoServer.exe -c -s"',creationflags=CREATE_NEW_CONSOLE)
  31. #subprocess.Popen(['runas', '/user:Administrator', '"CoreServer.exe -c -s"'],creationflags=CREATE_NEW_CONSOLE
  32. if(not isExistCoreServer):
  33. if(os.path.isfile(pathOfCorecsProjFile)):
  34. os.chdir(msBuildPath)
  35. startCommand="start cmd /c"
  36. command="MSBuild.exe "+pathOfCorecsProjFile+" /t:build /p:configuration=Debug"
  37. #os.system(startCommand+command)
  38. cmd=subprocess.Popen(startCommand+command)
  39. if(not isExistEchoServer):
  40. if(os.path.isfile(pathOfEchocsProjFile)):
  41. os.chdir(msBuildPath)
  42. startCommand="start cmd /c"
  43. command="MSBuild.exe "+pathOfEchocsProjFile+" /t:build /p:configuration=Debug"
  44. os.system(startCommand+command)
  45. if(isExistCoreServer and isExistEchoServer):
  46. OpenServers()
  47. else:
  48. # Re-run the program with admin rights
  49. 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方法

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

Python 3-3.4

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

  1. import subprocess
  2. output = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
  3. 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

  1. import subprocess
  2. result = subprocess.run(['CoreServer.exe', '-c', '-s'], stdout=subprocess.PIPE)
  3. 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

  1. import subprocess
  2. output = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
  3. 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:

确定