读取从打开新命令提示符的 os.Popen 中的文本

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

Read text from os.Popen that opens new command prompt

问题

import os
import subprocess
import time
import ctypes, sys

需要以管理员权限运行此脚本以打开命令提示符窗口

def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False

if is_admin():
# 仅当具有管理员特权时才能运行程序。

  1. # 获取脚本所在目录。
  2. currentDirectory = os.path.dirname(os.path.abspath(__file__)
  3. coreServerFullPath = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer/bin\Debug")
  4. isExistCoreServer = os.path.exists(coreServerFullPath)
  5. echoServerFullPath = os.path.join(currentDirectory, "Echo\Server\EchoServer/bin\Debug")
  6. isExistEchoServer = os.path.exists(echoServerFullPath)
  7. # 这是MSBuild.exe的路径,以后我们可以获取MSBuild.exe作为独立程序并更改路径。
  8. msBuildPath = "C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
  9. pathOfCorecsProjFile = os.path.join(currentDirectory, "Core\CoreServer\Server\CoreServer\CoreServer.csproj")
  10. pathOfEchocsProjFile = os.path.join(currentDirectory, "Echo\Server\EchoServer\EchoServer.csproj")
  11. def OpenServers():
  12. os.chdir(coreServerFullPath)
  13. # os.system("start /wait cmd /c {command}")
  14. command_line = [coreServerFullPath, '-c', '-s']
  15. result = subprocess.Popen(['start', 'cmd', '/k', 'CoreServer.exe -c -s'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
  16. time.sleep(4)
  17. output = result.stdout.read()
  18. print(output)
  19. def Test():
  20. os.chdir(coreServerFullPath)
  21. output = subprocess.check_output(['CoreServer.exe', '-c', '-s'], shell=True)
  22. time.sleep(4)
  23. print(output)
  24. def Test1():
  25. os.chdir(coreServerFullPath)
  26. result = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
  27. print(result.stdout)
  28. if (not isExistCoreServer):
  29. if (os.path.isfile(pathOfCorecsProjFile)):
  30. os.chdir(msBuildPath)
  31. startCommand = "start cmd /c"
  32. command = "MSBuild.exe " + pathOfCorecsProjFile + " /t:build /p:configuration=Debug"
  33. # os.system(startCommand+command)
  34. cmd = subprocess.Popen(startCommand + command)
  35. if (not isExistEchoServer):
  36. if (os.path.isfile(pathOfEchocsProjFile)):
  37. os.chdir(msBuildPath)
  38. startCommand = "start cmd /c"
  39. command = "MSBuild.exe " + pathOfEchocsProjFile + " /t:build /p:configuration=Debug"
  40. os.system(startCommand + command)
  41. if (isExistCoreServer and isExistEchoServer):
  42. Test1()

else:
# 以管理员权限重新运行程序
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

英文:

I am using os.Popen to open a new command prompt window and run a process. How can I read the text within that command prompt?

  1. import os
  2. def OpenServers():
  3. os.chdir(coreServerFullPath)
  4. process=os.popen("start cmd /K CoreServer.exe -c -s").read()
  5. print(process) #Prints nothing

This is the output text that's shown in the command prompt which I want to print.

读取从打开新命令提示符的 os.Popen 中的文本

Edit

I also tried this way, but no luck

  1. from subprocess import Popen, PIPE, STDOUT
  2. def OpenServers():
  3. os.chdir(coreServerFullPath)
  4. result = subprocess.Popen(['start', 'cmd', '/k', 'CoreServer.exe -c -s'], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  5. time.sleep(4)
  6. output=result.stdout.read()
  7. print(output) #Prints nothing

Edit 2

I tried something like this. Problem is, it makes me run 2 times. The first time when I run, the console is blank. The second time when I run it works but gives me an error because I can only open one instance of the server,.

  1. def Test1():
  2. os.chdir(coreServerFullPath)
  3. result = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
  4. print(result.stdout)

Here is the full code that I was trying. I can run CoreServer only as an admin so doing it like this

  1. import os
  2. import sys
  3. import subprocess
  4. from subprocess import Popen, CREATE_NEW_CONSOLE
  5. from subprocess import Popen, PIPE, STDOUT
  6. import time
  7. import ctypes, sys
  8. #The command prompts must be opened as administrators. So need to run the python script with elevated permissions. Or else it won't work
  9. def is_admin():
  10. try:
  11. return ctypes.windll.shell32.IsUserAnAdmin()
  12. except:
  13. return False
  14. if is_admin():
  15. #The program can only run with elevated admin privileges.
  16. #Get the directory where the file is residing.
  17. currentDirectory=os.path.dirname(os.path.abspath(__file__))
  18. coreServerFullPath=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer/bin\Debug")
  19. isExistCoreServer=os.path.exists(coreServerFullPath)
  20. echoServerFullPath=os.path.join(currentDirectory,"Echo\Server\EchoServer/bin\Debug")
  21. isExistEchoServer=os.path.exists(echoServerFullPath)
  22. #For now this is the MSBuild.exe path. Later we can get this MSBuild.exe as a standalone and change the path.
  23. msBuildPath="C:\Program Files (x86)\Microsoft Visual Studio/2019\Professional\MSBuild\Current\Bin/amd64"
  24. pathOfCorecsProjFile=os.path.join(currentDirectory,"Core\CoreServer\Server\CoreServer\CoreServer.csproj")
  25. pathOfEchocsProjFile=os.path.join(currentDirectory,"Echo\Server\EchoServer\EchoServer.csproj")
  26. def OpenServers():
  27. os.chdir(coreServerFullPath)
  28. #os.system("start /wait cmd /c {command}")
  29. command_line = [coreServerFullPath, '-c', '-s']
  30. result = subprocess.Popen(['start', 'cmd', '/k', 'CoreServer.exe -c -s'], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  31. time.sleep(4)
  32. output=result.stdout.read()
  33. print(output)
  34. #process=os.popen("start cmd /K CoreServer.exe -c -s").read()
  35. #print(process)
  36. def Test():
  37. os.chdir(coreServerFullPath)
  38. output = subprocess.check_output(['CoreServer.exe', '-c', '-s'],shell=True)
  39. time.sleep(4)
  40. print(output)
  41. def Test1():
  42. os.chdir(coreServerFullPath)
  43. result = subprocess.check_output(['CoreServer.exe', '-c', '-s'])
  44. print(result.stdout)
  45. if(not isExistCoreServer):
  46. if(os.path.isfile(pathOfCorecsProjFile)):
  47. os.chdir(msBuildPath)
  48. startCommand="start cmd /c"
  49. command="MSBuild.exe "+pathOfCorecsProjFile+" /t:build /p:configuration=Debug"
  50. #os.system(startCommand+command)
  51. cmd=subprocess.Popen(startCommand+command)
  52. if(not isExistEchoServer):
  53. if(os.path.isfile(pathOfEchocsProjFile)):
  54. os.chdir(msBuildPath)
  55. startCommand="start cmd /c"
  56. command="MSBuild.exe "+pathOfEchocsProjFile+" /t:build /p:configuration=Debug"
  57. os.system(startCommand+command)
  58. if(isExistCoreServer and isExistEchoServer):
  59. Test1()
  60. else:
  61. # Re-run the program with admin rights
  62. ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

答案1

得分: 1

对于这种情况,获取输出的最佳方法是将其转储到日志文件中,然后从文件中读取输出。(最好在运行程序之前创建日志文件)

这里有一个简单的示例:

  1. result = subprocess.Popen('start cmd /k CoreServer.exe -c -s >> log.log 2>&1', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  2. time.sleep(4)
  3. with open('log.log', 'r') as logg:
  4. print(logg.read())

这应该打印出所需的输出。希望对你有帮助。

英文:

For this type of situations the best way to get the output is to dump it to a log file and then read the output from the file. (Is better to create the log file before running the program)

Here you have a simple example:

  1. result = subprocess.Popen('start cmd /k CoreServer.exe -c -s >> log.log 2>&1', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  2. time.sleep(4)
  3. with open('log.log', 'r') as logg:
  4. print(logg.read())

This should print the desired output. Hope it works for you.

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

发表评论

匿名网友

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

确定