I am trying to automate fdisk utility on Linux in order to delete partitions on the attached disk device (USB /dev/sdb in this case) by using Python 3.
The script should execute the following commands:
1). sudo fdisk /dev/sdb // Executing fdisk on /dev/sdb
Welcome to fdisk (util-linux 2.29). Changes will remain in memory only, until you decide to write them. Be careful before using the write command.
Command (m for help): 2). d /dev/sdb // Trying to delete /dev/sdb partition.
Partition number (1-4, default 4): 3). 2 // Partition number 2
This is my Python code so far:
proc = subprocess.Popen(["sudo", "fdisk", "/dev/sdb"], stdin=subprocess.PIPE)
proc.communicate(b'd /dev/sdb')
proc.communicate(b'2')
Line1 and Line2 works perfectly fine, however Line3 gives me the following error:
Welcome to fdisk (util-linux 2.29).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help): Partition number (1-4, default 4): Traceback (most recent call last):
File "./testing.py", line 83, in <module>
proc.communicate(b'2')
File "/usr/lib/python3.5/subprocess.py", line 786, in communicate
self._stdin_write(input)
File "/usr/lib/python3.5/subprocess.py", line 741, in _stdin_write
self.stdin.write(input)
ValueError: write to closed file
Is it possible to use subprocesses to achieve this task without a user having to interact with the program? Any assistance will be highly appreciated. Thanks.