如何在python中打开cmd并运行ipconfig [英] How to open cmd and run ipconfig in python

查看:82
本文介绍了如何在python中打开cmd并运行ipconfig的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个执行类似操作的脚本:打开 cmd 并运行命令ipconfig",然后复制我的 ip 并将其粘贴到文本文件中.我写了脚本的开头,但没有得到我想要的结果.这是脚本的开头:

I would like to write a script that do something like that: open the cmd and run the commend "ipconfig" and than copy my ip and paste it to a text file. I wrote the beginning of the script but I didn't get the results that I wanted. Here is the start of the script:

import os
f = os.system("cmd/ipconfig")

我得到而不是得到 ipconfig 输出:

I got instead of getting the ipconfig output:

Microsoft Windows [Version 10.0.15063]
???(c) 2017 Microsoft Corporation. �� ������� ������.

C:\Users\vespper\PycharmProjects\toturial>

推荐答案

如果您想获取 IP 地址,请这样做

If you are trying to get IP address only do like this

import socket
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]

如果您真的想按照您尝试的方式执行 ipconfig,请执行此操作以获得输出

If you really want to execute ipconfig the way you are trying, do this to get output

import subprocess
proc = subprocess.check_output("ipconfig" ).decode('utf-8')
print (proc)

这篇关于如何在python中打开cmd并运行ipconfig的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆