在sh python modu中实现git添加/提交的问题

2024-10-02 18:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用sh python模块的git时遇到以下奇怪的行为:

下面是python脚本:

import sh
from datetime import datetime

now = str(datetime.now())

filename = "config.cfg"
file = filename
f = open(file, 'w')
f.write(now)

now = str(datetime.now())
comment = "-m " + "\"new version" + " registrered " + now + "\""


print(sh.sudo.git("add", filename))
print(sh.sudo.git("commit", comment))

行为: 手动操作一切正常:

^{pr2}$

但不是通过pythonsh模块实现的

第一次执行可以

python sh1.py
[master 6d13519]  "new version registrered 2014-10-24 15:37:42.534595"
 1 file changed, 1 deletion(-)

II-####################

python sh1.py

Traceback (most recent call last):
  File "sh1.py", line 24, in <module>
    print(sh.sudo.git("commit", comment))
  File "/home/user/anaconda/lib/python2.7/site-packages/sh.py", line 769, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/home/user/anaconda/lib/python2.7/site-packages/sh.py", line 330, in __init__
    self.wait()
  File "/home/user/anaconda/lib/python2.7/site-packages/sh.py", line 334, in wait
    self._handle_exit_code(self.process.wait())
  File "/home/user/anaconda/lib/python2.7/site-packages/sh.py", line 348, in _handle_exit_code
    self.process.stderr
sh.ErrorReturnCode_1: 

  RAN: '/usr/bin/sudo git commit -m "new version registrered 2014-10-24 15:38:02.528213"'

  STDOUT:
On branch master
Untracked files:
    sh1.py

nothing added to commit but untracked files present


  STDERR:

III-####################

$ sudo git add config.cfg

$ sudo git commit -m "new version registrered 2014-10-24 15:34:35.2415245"
[master 5d5fe35] new version registrered 2014-10-24 15:34:35.2415245
 1 file changed, 1 insertion(+)

现在回到第一行为,等等。。。在


用户在sudoers中并设置NOPASSWD以避免sudo密码


Tags: inpygitnewdatetimeversionshline
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:36

在调用git命令之前,需要关闭file对象。在

f.close()

如果您运行“git status”,您会看到git在脚本运行后抱怨,配置.cfg仍然有一些未准备好提交的更改。在

我有一种感觉,当文件关闭时,python会将一个EOF字符或其他内容刷新到文件中,因此会更改文件,因为您从脚本中调用了'git add',因此更改了文件。很遗憾,我不知道这个问题是在我从脚本中的“git add”“git commit”之前关闭文件时解决的。在

编辑: 无用已纠正我,并指出原因是因为文件是缓冲的。在

相关问题 更多 >