1

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

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.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"

回溯(最后一次调用):文件“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 errread, errwrite) 文件“/usr/local/pythonbrew/pythons/Python-2.7/lib/python2.7/subprocess .py",第 1201 行,在 _execute_child raise child_exception OSError: [Errno 2] No such file or directory

4

1 回答 1

0

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

StringIO 模块包含一个名为 StringIO 的类,它为内存中的字符串提供类似文件的接口。

将这两个部分组合在一起,您可以将特定字符串发送到 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')
于 2016-01-13T22:09:29.170 回答