-1

How to make Python script flow like git commit?

For example if I write

git commit -m 'Commit message'

I create commit with this message. And if I write just

git commit

git suggest me to enter commit-message in text editor such VIM.

mikatakana
  • 503
  • 9
  • 22
  • possible duplicate of [How can I process command line arguments in Python?](http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python) or http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scri. Check also http://stackoverflow.com/questions/1009860/command-line-arguments-in-python?rq=1 – fredtantini Dec 17 '14 at 10:38
  • I don't believe this is a duplicate of either of the mentioned questions. – Wander Nauta Dec 17 '14 at 10:46
  • are you asking how to parse arguments? Are you asking how to open up a text editor? It's unclear what you're asking. – Bryan Oakley Dec 20 '14 at 18:08
  • I'm asking how to pass arguments via text editor – mikatakana Dec 24 '14 at 05:59

1 Answers1

2

Git's commit command, when not given a -m flag, calls your preferred editor with a temporary file, waits for the editor to exit, then reads out the file.

In Python, you would use os.system or the more modern subprocess library. Both will wait for the subprocess to end.

import subprocess, tempfile

tmpfile = tempfile.NamedTemporaryFile()
subprocess.call(["vim", tmpfile.name])
print("You wrote", tmpfile.read())
tmpfile.close()

(Of course, this example assumes that your preferred editor is Vim.)

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • thanks for reply? I will try your method. So I've updated question with some code. Looks it like right way too? – mikatakana Dec 17 '14 at 10:53
  • your code returns "You wrote b''" in Python 3 version – mikatakana Dec 17 '14 at 10:56
  • Your code seems to do about the same thing, but it has some issues. It'll probably work, but it won't clean up the temporary file if it happens to crash, running multiple instances of the script at the same time will cause them to overwrite one another's files, and it won't work if you don't have write access to the current directory. – Wander Nauta Dec 17 '14 at 11:05
  • I've wrote `with open(tmpfile.name, 'r') as fp: data = fp.read()` instead of read() – mikatakana Dec 17 '14 at 11:12
  • Yes, I saw that. Sadly, that doesn't fix the problem I was referring to: if your code throws an exception inside the `with` block, your temporary file will not be deleted. – Wander Nauta Dec 17 '14 at 11:19