Search code examples
pythonbashshellsubprocess

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?


Solution

  • 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"