英文:
How do I run bash shell commands with subprocess in Python?
问题
import subprocess
subprocess.run(["IFS=$'\n'", "for i in $(grep ^id= /etc/NetworkManager/system-connections/*.nmconnection | cut -d= -f2); do", "nmcli connection modify \"$i\" ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no;", "done"])
英文:
I have the follow bash shell command. I want to run it with subprocess.run in python.
subprocess.run([.....])
Below is bash shell command
IFS=$'\n'
for i in $(grep ^id= /etc/NetworkManager/system-connections/*.nmconnection | cut -d= -f2); do \
nmcli connection modify "$i" ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no; \
done
答案1
得分: 2
将所有内容放入一个字符串中,然后将其作为-c
参数传递给bash
。
cmd = r"""
IFS=$'\n'
for i in $(grep ^id= /etc/NetworkManager/system-connections/*.nmconnection | cut -d= -f2); do \
nmcli connection modify "$i" ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no; \
done
"""
subprocess.run(["bash", "-c", cmd])
英文:
Put it all in a string and then pass that as a the -c
argument to bash
.
cmd = r"""IFS=$'\n'
for i in $(grep ^id= /etc/NetworkManager/system-connections/*.nmconnection | cut -d= -f2); do \
nmcli connection modify "$i" ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no; \
done
"""
subprocess.run(["bash", "-c", cmd])
答案2
得分: 1
以下是翻译好的部分:
与直接在subprocess.run
调用中运行bash脚本不同,您可以在Python中执行循环。
一种方法是:
import glob
import re
cmd_pre = "nmcli connection modify"
cmd_suf = "ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no"
glob_str = "/etc/NetworkManager/system-connections/*.nmconnection"
regex = re.compile(r"id=(\w+)")
for fn in glob.glob(glob_str):
matches = [re.match(regex, l) for l in open(fn)]
names = [m.groups(1)[0] for m in matches if m is not None]
for name in names:
subprocess.run(" ".join([cmd_pre, name, cmd_suf]))
英文:
Rather than run the bash script directly in the subprocess.run
call, you could perform the looping in Python.
One way to do this would be:
import glob
import re
cmd_pre = "nmcli connection modify"
cmd_suf = "ipv4.dhcp-send-hostname no ipv6.dhcp-send-hostname no"
glob_str = "/etc/NetworkManager/system-connections/*.nmconnection"
regex = re.compile(r"id=(\w+)")
for fn in glob.glob(glob_str):
matches = [re.match(regex, l) for l in open(fn)]
names = [m.groups(1)[0] for m in matches if m is not None]
for name in names:
subprocess.run(" ".join([cmd_pre, name, cmd_suf]))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论