How do I pass variable when using Python subprocess module

和自甴很熟 提交于 2020-12-21 04:20:03

问题


I'm trying to use python Subprocess module to enable/disable Ethernet connection from python code. Below is my code in which the first step is looking for the available "Ethernet Connections" and the next step enables/disables the ethernet connection according to the parameter passed in "%interfaces%".

for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do set interface=%%B

netsh interface set interface %interface%  ENABLED

Now when using in python I couldn't pass the variable, not sure if it's even possible though. Passing only command as below works as expected:

import subprocess
subprocess.call('netsh interface set interface Ethernet10 ENABLED')

I want to do something like:

import subprocess
subprocess.call (set x = 'Ethernet0')
subprocess.call('netsh interface set interface x  ENABLED')

回答1:


subprocess.call takes a list as an argument:

subprocess.call(['netsh', 'interface', 'set', 'interface', x, 'ENABLED'])

You could instead pass shell=True and your string would work, but it is a security risk, since an user could for example call another command by using $(command_here)

If you still want to use a string, you could use shlex.split.




回答2:


Use string formatting, interpolation, or concatenation:

x = 'Ethernet10'
subprocess.call('netsh interface set interface ' + x + ' ENABLED')


来源:https://stackoverflow.com/questions/40390983/how-do-i-pass-variable-when-using-python-subprocess-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!