-1

I have the following code line:

run_command('/usr/bin/msgabc -A30 --before "/etc/conf/help.txt" &')

And I would like to write it the "correct way" by using constants and make it more generic.
I have tried to transform it into the following piece of code:

import os
MSGABC_PATH = "/usr/bin"
MSGABC_BINARY = "msgabc"
MSGABC_COMMANDLINE_ARGS = "-A30 --before \"/etc/conf/help.txt\""

run_command("%s %s &" % (os.path.join(MSGABC_PATH, MSGABC_BINARY), MSGABC_COMMANDLINE_ARGS)

But the latter makes it less readable for the new reader.
Which method would be the most generic without losing readability?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Bojangles
  • 39
  • 4
  • 3
    What's wrong with the first method? If none of the parts of the string as you've broken them out in the second method are likely to change I see no harm at all in the first method. – Jamie Scott Nov 07 '18 at 14:33
  • 1
    Hardcoding the path `/usr/bin` is a bit of a wart, though, and hard-coding the `&` looks iffy to me. Maybe use `subprocess.Popen(['msgabc', '-A30', '--before', '/etc/conf/help.txt'])` - notice how, in the absence of `shell=True` you should not - and cannot - use shell quoting around arguments. You'll need to manage the process yourself, though (at least `wait` for it to eventually complete). – tripleee Dec 12 '18 at 15:09

1 Answers1

0

AFAIK, there are no code conventions specifically for formatting command line strings. At least, PEP 8 doesn't say anything on this matter.

Though, the following string '/usr/bin/msgabc -A30 --before "/etc/conf/help.txt" &' is a hard-coded string, or a so-called "magic string". And these strings could cause some problems. See "What is wrong with magic strings?" for discussion.

So, the best course of action would be to make it constant. And it is unnecessary to split it to substrings and make all of them constants. Doing so doesn't have any benefits in your particular case and only hurts readability.

MSGABC_COMMAND = '/usr/bin/msgabc -A30 --before "/etc/conf/help.txt" &'

run_command(MSGABC_COMMAND)

Though, some people think that if a hard-coded string is encountered only once, it is unnecessary to make it constant, and you can leave it as it is: Are hard-coded STRINGS ever acceptable?

Georgy
  • 12,464
  • 7
  • 65
  • 73