iTikoz
iTikoz

Reputation: 113

Run a bash command in a subprocess with a variable argument

I am running a Python script on Centos, which has some Bash commands using subprocess:

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

I am importing the variables from a config file.

How to pass the "new-hostname" as a variable "host" to the command I am executing, which could be dynamically assigned from the config file?

Upvotes: 0

Views: 1077

Answers (2)

tripleee
tripleee

Reputation: 189799

If you know the last item in the list is the hostname, just replace that.

Tangentially, you want shlex.split() over regular .split() for command lines (the shlex one copes correctly with backslashes, quoting, etc) and you want subprocess.run instead of bare Popen + communicate when the task is simply to run a subprocess and wait for it to complete.

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

Alternatively, assemble the command from parts.

command = ["sudo", "hostnamectl", "set-hostname"]
subprocess.run(command + [host], text=True, capture_output=True, check=True)

Upvotes: 0

Nullman
Nullman

Reputation: 4279

It seems like you just want to assemble a string, you can use the format command:

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

should give you what you want, if you are using a fairly recent version of python(3.6.4+ iirc) you can also do:

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

Upvotes: 1

Related Questions