如何在 Windows 10 中从 Python 调用 cmd.exe

问题描述 投票:0回答:1

我很难从 Python 调用 cmd.exe。 到目前为止,有两次尝试:

  command = r'dir "D:\tmp 1\tmp 2" > "D:\tmp 1\tmp 2\dir.txt"'
  command = r'dir "D:"'
  print(command)
  status = subprocess.call(["cmd.exe", "/c", command])
  if status == 0:
    print("Command executed.")
  else:
    print("Error:", status)

def call_cmd_demo2():
  mycommand = r'cmd.exe dir "D:\tmp 1\tmp 2" > "D:\tmp 1\tmp 2\dir.txt"'
  mycommand = r'cmd.exe dir "D:"'
  print(mycommand)
  status = os.system(mycommand)
  if status == 0:
    print("Command executed.")
  else:
    print("Error:", status)

command = r'dir "D: mp 1 mp 2" > "D: mp 1 mp 2\dir.txt"'

包括重定向,由于超出我的技能范围的原因,这恰好是另一个级别的困难。我开始使用更简单的命令的原因。

第一个版本在文件夹名称上产生语法错误(请注意,当粘贴到终端中时,命令本身运行顺利)

第二个版本挂起。

python-3.x windows cmd
1个回答
0
投票
    """
Module containing utility functions for executing system commands (Windows 10)
"""

from subprocess import run, CompletedProcess
from typing import Any
from utils import display_function_name

def execute(command: str) -> CompletedProcess:
  """
  Executes a DOS command in a console,
  Returns the result as a CompletedProcess object
  EXAMPLE:
  result: str = execute('echo Hello World').stdout
  print(result)

  :param command: The DOS command to execute
  :return: CompletedProcess object
  """
  result: CompletedProcess = run(command, shell=True, capture_output=True, text=True, encoding='cp850')
  return result


def execute_demo():
  for command in [
      r"""echo Hêllo to the ñew wörld""",
      r"""dir""",
      r"""dir "C:\" """]:
    print("\nCommand:" + command)
    print(f"Output:{execute(command).stdout}")
© www.soinside.com 2019 - 2024. All rights reserved.