Home > Software engineering >  python how to pass variable in to os.system command
python how to pass variable in to os.system command

Time:08-11

here is simple example how to re-scan disk sda from python script

#!/usr/bin/python3

import subprocess
import os



command = "echo 1 > /sys/block/sda/device/rescan"
os.system(command)

in case we want to set the disk as variable as disk_name

#!/usr/bin/python3

import subprocess
import os

disk_name = sda
command = "echo 1 > /sys/block/disk_name/device/rescan"
os.system(command)

then what is the rights approach to pass the disk_name variable in to command ? , or maybe other better approach ?

we tried as the following but without success

command = " 'echo 1 > /sys/block/'   str(disk_name)   '/device/rescan' "
os.system(command)

CodePudding user response:

Using your syntax (just remove the double-quotes, there is your mistake):

command = 'echo 1 > /sys/block/'   str(disk_name)   '/device/rescan'
os.system(command)

But you can use an F-string to make it cleaner:

command = F"echo 1 > /sys/block/{disk_name}/device/rescan"
os.system(command)
  • Related