Using subprocess.call() to pass commands to execut

2019-09-17 03:05发布

问题:

I am trying to set my IP address to a specific one on a LAN Network.

To do this i have tried using the following:

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])

The only thing this results in is the starting up of an empty cmd.exe that isn't doing anything.

Also, what for would the shell=True be used ? When I try to use it, python returns a SyntaxError

UPDATE: If I use:

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 Returns the error:

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

回答1:

If you use a string of args you need 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)

You can do it without shell=True which I would recommend by passing a list of args:

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)

Or let shlex.split split the args for you:

import shlex

subprocess.call(shlex.split(command))

using check_call in place of call may also be preferable as call will not raise an error if there is a non-zero exit status where check_call will.



回答2:

If there is netsh.exe somewhere in the search path (assuming you are on Windows) then you could pass the command string as is:

import subprocess

subprocess.check_call(command)