如何在Python中使用subprocess运行bash shell命令?

huangapple go评论61阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月17日 22:19:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定