Yes, the way you do it is a good way (there is no "right way" in programming, because you can always do one thing in at least two ways, which both have their pros and cons !). But you first should put your path in quotes so that it is a string (Right now it's a non existent invalid variable name which will raise a SyntaxError
). Then, you have multiple possibilities to put the variables into the path:
- Use string interpolation:
"/Users/ngupta59/code/python-prm-example-agent/%s.%s.req" % (str(self.spec.serviceid), str(self.spec.msid))
- Use f-strings (only available in Python >= 3.6):
f"/Users/ngupta59/code/python-prm-example-agent/{str(self.spec.serviceid)}.{str(self.spec.msid)}.req"
- Concatenate the path components together, I don't like this way because you have to type in so many + signs and quotes:
"/Users/ngupta59/code/python-prm-example-agent/" + str(self.spec.serviceid) + "." + str(self.spec.msid) + ".req"
- Use
str.format
, but I never used it because I think percent sign substitution anf f-strings are better.
If you want code that is runnable with Python 3 and Python 2, use string interpolation. If you want obvious and easy-to-understand code, use f-strings.
A side note: Every argument for subprocess.run
should be put into a separate string. Here is the complete code using f-strings:
result = subprocess.run(
[
"cat",
"`date`"
">",
f"/Users/ngupta59/code/python-prm-example-agent/{str(self.spec.serviceid)}.{str(self.spec.msid)}.req",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)