使用subprocess.call()传递命令以通过cmd执行

时间:2015-02-15 18:02:54

标签: python-2.7 powershell cmd arguments subprocess

我正在尝试将我的IP地址设置为LAN网络上的特定IP地址。

要做到这一点,我尝试使用以下内容:

import subprocess
command='netsh interface ipv4 set address name="Local Area Connection* 4" source=static address=192.168.173.234 mask=255.255.255.0 gateway=192.168.0.1'
subprocess.call(["cmd.exe", command])

唯一导致的是启动一个没有做任何事情的空cmd.exe。

另外,shell = True会用到什么? 当我尝试使用它时,python返回一个SyntaxError

更新:如果我使用:

command='netsh interface ipv4 set address name="Local Area Connection* 4" source=static address=192.168.173.222 mask=255.255.255.0 gateway=192.168.0.1'
subprocess.check_call(["netsh.exe", command])

Python返回错误:

Traceback (most recent call last):
  File "D:file path", line 8, in <module>
    subprocess.check_call(["netsh.exe", netsh_cmd])
  File "C:\Python27\lib\subprocess.py", line 540, in check_call
    raise CalledProcessError(retcode, cmd)
CalledProcessError: Command '['netsh.exe', 'netsh interface ipv4 set address name="Local Area Connection* 4" source=static address=192.168.173.222 mask=255.255.255.0 gateway=192.168.0.1']' returned non-zero exit status 1

2 个答案:

答案 0 :(得分:0)

如果你使用一串args,你需要shell=True

import subprocess
command="netsh interface ipv4 set address name='Local Area Connection* 4' source=static address=192.168.173.234 mask=255.255.255.0 gateway=192.168.0.1"
subprocess.call(command,shell=True)

你可以在没有shell=True的情况下通过传递args列表来推荐{<1}}。

import subprocess
command = ['netsh', 'interface', 'ipv4', 'set', 'address', 'name=Local Area Connection* 4', 'source=static', 'address=192.168.173.234', 'mask=255.255.255.0', 'gateway=192.168.0.1']


subprocess.call( command)

或者让shlex.split为你分割args:

import shlex

subprocess.call(shlex.split(command))

使用check_call代替呼叫也可能更好,因为如果check_call存在非零退出状态,则call不会引发错误。

答案 1 :(得分:0)

如果the search path中某处netsh.exe(假设您在Windows上),则可以按原样传递命令字符串:

import subprocess

subprocess.check_call(command)
相关问题