用 python 运行 cmd 命令 
时间: 2023-03-20 22:01:35 浏览: 153
可以使用 Python 中的 `subprocess` 模块来运行 cmd 命令。具体步骤如下:
1. 首先需要导入 `subprocess` 模块:
```python
import subprocess
```
2. 然后使用 `subprocess.run()` 函数来运行 cmd 命令,将命令作为字符串传递给该函数。例如,运行 `dir` 命令可以这样写:
```python
subprocess.run('dir', shell=True)
```
注意要将 `shell` 参数设置为 `True`,以便在 Windows 系统上运行 cmd 命令。
3. `subprocess.run()` 函数默认情况下会在新的子进程中运行命令,并等待命令执行完毕。如果需要获取命令的输出,可以将 `capture_output` 参数设置为 `True`,并使用 `stdout` 属性来获取标准输出。例如,获取 `ipconfig` 命令的输出可以这样写:
```python
result = subprocess.run('ipconfig', capture_output=True, shell=True)
print(result.stdout.decode('gbk'))
```
注意要使用 `decode()` 函数将输出解码为字符串,并指定适当的编码方式。在 Windows 系统上,常用的编码方式是 `gbk`。
相关问题
python 运行cmd命令后logging无法输出
当使用Python运行cmd命令后,由于cmd命令本身的输出是直接输出到标准输出流(stdout)中,而不是通过标准错误流(stderr)输出,因此无法直接通过logging模块来输出。
为了解决这个问题,我们可以使用subprocess模块的Popen类来执行cmd命令,并通过重定向方式将标准输出流改为标准错误流,从而能够通过logging模块来输出。
下面是一个示例代码:
```python
import subprocess
import logging
# 配置logging模块
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# 执行cmd命令,并将标准输出重定向到标准错误流
process = subprocess.Popen('cmd命令', stderr=subprocess.PIPE, shell=True)
# 读取标准错误流的输出
output, error = process.communicate()
# 将错误日志输出到logging模块
logging.error(output.decode('utf-8'))
```
在这个示例代码中,我们首先通过subprocess模块的Popen类执行cmd命令,将标准输出流重定向到标准错误流,并使用stderr参数来保证标准错误流的输出被捕获。
然后,通过process.communicate()方法来获取标准错误流的输出,将其解码为字符串,并使用logging模块的error()方法将其输出为错误日志。
通过以上方式,我们可以在Python中执行cmd命令时,将输出信息通过logging模块来进行输出。
cmd命令后台运行python脚本
在Windows系统中,可以使用以下方法在cmd命令行中后台运行Python脚本:
1. 使用pythonw.exe:在cmd命令行中输入以下命令:
```
pythonw your_script.py
```
这将在后台运行Python脚本。
2. 使用start命令:在cmd命令行中输入以下命令:
```
start /B python your_script.py
```
这将在后台运行Python脚本。
3. 使用任务计划程序:可以使用Windows的任务计划程序来定时运行Python脚本,并且可以选择在后台运行。打开任务计划程序,创建一个新任务,然后在触发器中设置脚本的运行时间,最后在操作中选择运行Python解释器并指定脚本的路径。
请注意,以上方法适用于Windows系统,对于Linux系统,可以使用nohup命令或者将脚本放在后台运行的进程中。\[2\]
#### 引用[.reference_title]
- *1* *2* *3* [在CMD命令行中运行python脚本的方法](https://blog.csdn.net/weixin_39638012/article/details/116281183)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
相关推荐









