0

I am new to python, want to make a file with variables name using as the name of the file-

For example two variables are - msid, serviceid File name should be serviceid.msid.req in some path with current date in it.

I have written this code -

result = subprocess.run(
    [
        "cat `date` > ",
        /Users/ngupta59/code/python-prm-example-agent/str(self.spec.serviceid).str(self.spec.msid).req,
    ],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)

Is this the correct way? Please help if you can

TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • If my answer helped you, please accept it using the grey checkmark on the left of it. This gives the author of the accepted answer +15 reputation, and the question author +2 reputation. – TheEagle Apr 15 '21 at 11:54
  • The same way that you would interpolate variables into any other string. – Karl Knechtel Apr 15 '21 at 12:00
  • I found the last of the duplicates I linked - along with many other potentially helpful resources - by literally copying and pasting your question title into a search engine. – Karl Knechtel Apr 15 '21 at 12:03

1 Answers1

1

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:

  1. Use string interpolation:
"/Users/ngupta59/code/python-prm-example-agent/%s.%s.req" % (str(self.spec.serviceid), str(self.spec.msid))
  1. 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"
  1. 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"
  1. 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,
)
TheEagle
  • 5,808
  • 3
  • 11
  • 39