subprocess.call 用于执行 "ci -u <filename>" 的命令

subprocess.call command for executing "ci -u <filename>"

我正在尝试执行一个 python 脚本,该脚本首先创建一个新文件(如果它不存在)然后执行 ci(在新创建的文件上)以创建一个 rcs 文件带有初始修订号。但是当我 运行 脚本时,它要求我提供描述并以句点“.”结尾。我希望这部分使用默认描述自动执行,并在没有用户输入的情况下创建 rcs 文件。如有任何帮助,我们将不胜感激ci。以下是我的代码:

import os
import subprocesss

if os.path.isfile(location):

    print "File already exists"

else:

    f = open(location,'a')
    subprocess.call(["ci", "-u", location])
    f.close()
    print "new file has been created"

我试过了,但出现以下错误:

进口os

导入子进程

if os.path.isfile(位置):

    print "File already exists"

其他:

    f = open(location,'a')
    cmd = "ci -u "+location
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
    stdout_data = p.communicate(input='change\n.')[0]
    f.close()
    print "new file has been created"

Traceback(most 最近一次调用): 文件 "testshell.py",第 15 行,位于 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) 文件“/usr/local/pythonbrew/pythons/Python-2.7/lib/python2.7/subprocess.py”,第 672 行,在 init 中 读错,写错) 文件“/usr/local/pythonbrew/pythons/Python-2.7/lib/python2.7/subprocess.py”,第 1201 行,在 _execute_child 中 提高 child_exception OSError: [Errno 2] 没有那个文件或目录

您可以使用 subprocess.call 的标准输入参数为子进程提供一个 file-like 对象作为其标准输入(您将手动输入的内容)。

StringIO 模块包含一个名为 StringIO 的 class,它为 in-memory 字符串提供 file-like 接口。

将这两个部分组合在一起可以让您将 specific 字符串发送到 ci,就好像用户手动输入它一样

from StringIO import StringIO
import subprocess

...

subprocess.call(['command', 'with', 'args'], stdin=StringIO('StandardInput'))

或者,正如 CharlesDuffy 所建议的,您可以使用 Popen 及其通信方法:

import subprocess
proc = subprocess.Popen(['command', 'with', 'args'],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate('StandardInput')