'How can subprocess be used in a class and tested in python
I have an executable that has many options and I wish to create classes. e.g. the exec has options that can copy rows of a file, rename parts of a file, compress file, count specific rows of a file, e.t.c. Each option has parameters. I am uncertain if I am going about it the wrong way but I want to use oop.
import subprocess
class ExecProcess:
def __init__(self, myfile, tempfile, outfile):
self.myfile = myfile
self.tempfile = tempfile
self.outfile = outfile
self.compressed_file = self.outfile + 'zip'
def copy(self, myfile):
temp_copy = subprocess.call(['executable', '-c', self.myfile, '-out', self.tempfile])
return temp_copy # should this be return self.tempfile which is the output?
def rename(self, myfile, tempfile, outfile): # need to include all the variables I declared in init?
output = subprocess.call(['executable', '-i', self.myfile, '-r', self.tempfile'-out', self.compressed_file])
return output # return self.outfile?
Given the above, how do I call the methods within the class and then write tests for them e.g using pytest. Its not intuitive to me how to test subprocess calls using pytest
The results of each call is a different file each time with each subsequent command taking the file from an earlier command as input. Please note, myfile is the only original file I have. tempfile and outfile are just variable names I assigned to the results.
Any help will be appreciated
Solution 1:[1]
import subprocess
class Switch():
def __init__(self, ip):
self.ip = ip
self.subproc = subprocess
def ping(self):
success_ping = 0
for i in range(3):
status = self.subproc.call( ['ping', '-c', '1', '-W', '0.05', self.ip], stdout=self.subproc.DEVNULL )
if status == 0:
success_ping += 1
if success_ping > 0:
return True
else:
return False
def get_ip(self):
return ('Switch IP: '+self.ip)
sw = Switch('192.168.1.1')
if (sw.ping):
print('Switch', sw.get_ip(), 'UP')
else:
print('Switch', sw.get_ip(), 'DOWN')
Maybe this be helpful for you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | EnzoMike |