简体   繁体   English

使用 Python 子进程模块向 cmd 提示符发送命令

[英]Send commands to cmd prompt using Python subprocess module

using python 3.7使用 python 3.7

I have the following issue: I wrote a python script in which I open a cmd prompt, do some actions then I want to send some commands to that opened cmd prompt我有以下问题:我写了一个 python 脚本,在其中打开 cmd 提示符,执行一些操作然后我想向打开的 cmd 提示符发送一些命令

To simplify, it looks something like:为了简化,它看起来像:

import subprocess
process = subprocess.Popen(['start','cmd','/k','dir'], shell = True, stdin= subprocess.PIPE, 
stdout = subprocess.PIPE, text = True)

"DO some actions"

input = 'date'
process.stdin.write(input)
process.communicate(input, timeout = 10)

All the time the script exits with exception TimeoutExpired, and in the cmd prompt i do not see command written (the input)脚本一直退出并出现 TimeoutExpired 异常,并且在 cmd 提示符下我没有看到写入的命令(输入)

I looked in the documentation, but i am new with python and did not understood very well how to use the subprocess module我查看了文档,但我是 python 的新手,不太了解如何使用子流程模块

Thank you for the support!谢谢你的支持!

If you want to write something like date in another cmd tab, do like this:如果你想在另一个cmd选项卡中写入类似date的内容,请执行以下操作:

import subprocess
input = 'date'
subprocess.Popen(['start','cmd','/k','echo',input], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, text = True)

Result:结果:
在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM