在子进程中使用可变参数运行 bash 命令

问题描述 投票:0回答:2

我正在 Centos 上运行 Python 脚本,其中有一些使用

subprocess
的 Bash 命令:

import ConfigParser
import fileinput
import sys
import subprocess

config = ConfigParser.ConfigParser()
config.readfp(open(r'config.file'))
host = config.get('section-1', 'machine_hostname')

# changing the hostname of the machine

change_hostname = "sudo hostnamectl set-hostname new-hostname"
process = subprocess.Popen(change_hostname.split(), 
stdout=subprocess.PIPE)
output, error = process.communicate()

我正在从配置文件导入变量。

如何将“new-hostname”作为变量“host”传递给我正在执行的命令,该命令可以从配置文件动态分配?

python bash shell subprocess
2个回答
1
投票

看起来你只是想组装一个字符串,可以使用format命令:

change_hostname = "sudo {} set-hostname new-hostname".format(host)

应该给你你想要的,如果你使用的是相当新版本的python(3.6.4+ iirc),你也可以这样做:

change_hostname = f"sudo {host} set-hostname new-hostname"


0
投票

如果您知道列表中的最后一项是主机名,只需替换它即可。

切线,你想要

shlex.split()
而不是常规的
.split()
用于命令行(
shlex
可以正确处理反斜杠、引号等),并且在执行任务时你想要
subprocess.run
而不是裸露的
Popen
+
communicate
只是运行一个子进程并等待它完成。

change_hostname = "sudo hostnamectl set-hostname new-hostname"
command = shlex.split(change_hostname)
# or simply command = ["sudo", "hostnamectl", "set-hostname", "__placeholder__"]
command[-1] = host
result = subprocess.run(command, text=True, capture_output=True, check=True)
output, error = result.stdout, result.stderr

或者,从零件组装命令。

command = ["sudo", "hostnamectl", "set-hostname"]
subprocess.run(command + [host], text=True, capture_output=True, check=True)
© www.soinside.com 2019 - 2024. All rights reserved.