Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python + how to pass variable in to os.system command

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

we tried as the following but without success

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading