0

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?

2 Answers 2

1

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"

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.