0

In some of my python-scripts, I've put the line if __name__ == '__main__' in order to make the content only be executed, when the script is run itself as main-script (as opposed to being imported, see this explanation).

As I've found that out just recently, I wanted to add two informative comment-lines before that line using sed.

The lines I want to prepend are:

# Docs on scope of __name__ == "__main__": https://stackoverflow.com/a/419185/12298276
# -> Makes boolean "execute_in_script = True/False" obsolete

In order to accomplish this, I put up the following find - sed - command which shall make the desired change in all my python-scripts automatically:

find /home/andylu/Desktop/Python/Scripts/ -not -path "*.history*" -not -path '*__pycache__*' -type f -exec sed -i -Ee '/^if __name__ == '__main__':.*/i # Docs on scope of __name__ == "__main__": https://stackoverflow.com/a/419185/12298276\n# -> Makes boolean "execute_in_script = True/False" obsolete' {} \;

Unfortunately, it doesn't work. It seems to be running as it takes like 30 seconds to complete, but there is neither any output in the console, nor changes in the python-scripts.

How do I have to correct my sed-string, which is like /line of interest/i Lines to\nprepend before that line, to make it work?


Documentation on how to prepend or append lines with sed:

See this blog post.

2
  • 2
    Are you actually trying to match '__main__' or '__main__':? either way, single quotes don't nest, you'd need something like '/^if __name__ == '\''__main__'\''/i (there's no point matching a trailing .*) Dec 22, 2020 at 21:55
  • I tried to match '__main__': including the colon. Thanks to your hint I've got it working now. It's also useful to know that there's not reason for matching the rest of the entire line.
    – Andreas L.
    Dec 24, 2020 at 18:50

1 Answer 1

0

Thanks to the comment of @steeldriver I got it working with the following command:

andylu@andylu-Lubuntu-PC:~/$ find /home/andylu/Desktop/Python/Scripts/ -not -path "*.history*" -not -path '*__pycache__*' -type f -exec sed -i -Ee '/^if __name__ == '\''__main__'\''/i # Docs on scope of __name__ == "__main__": https://stackoverflow.com/a/419185/12298276\n# -> Makes boolean "execute_in_script = True/False" obsolete' {} \;

It was essential to replace the single-quotes ' inside the single-quoted regex-string with '\'' as

single quotes don't nest.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .