TypeError:bufsize必须为整数

时间:2018-07-11 10:09:02

标签: python-3.x subprocess runtime-error

我正在尝试编写一个可以从命令行运行的脚本,该脚本读取文本文件的内容,对其执行一些操作(将内容提供给可执行文件等)并写入结果到目标文件夹中的两个不同文件。脚本如下:

    #! /usr/local/bin/python3 python

import os, sys, re, subprocess


def read_txt(filepath, suffix=".txt"):
    """
    Reads and returns the contents of a MCMakeProblem compatible text file,
    after replacing "#filename"-line in the contents.
    :param filepath:
    :param suffix:
    :return:
    """
    filename = filepath.split("/")[-1][:-len(suffix)]  # The filename without the suffix and the preceding path
    print(filename)
    with open(f"{filepath}", 'r') as f:
        filecontents = f.read()
        filecontents = re.sub(r"#filename (.*)\n", f"#filename {filename}\n", filecontents)
    # print(filecontents)
    return filecontents


def create_HTML_folder(directory="./HTMLfiles"):
    """
    Creates a directory for a HTML file if it doesn't already exist.
    :param directory:
    :return:
    """
    try:
        print("Attempting to create a folder for the HTML files...")
        os.mkdir(directory)
    except:
        print("The folder already exists. Moving along...")


def redirect_HTML(htmlfile, destination="./HTMLfiles"):
    """
    This is for cleaning purposes. Moves a give HTML file to a sub-directory.
    :param htmlfile:
    :param destination:
    :return:
    """
    os.rename(htmlfile, f"{destination}/{htmlfile}")


def feed_txt_to_MakeProblem(filecontents):
    """
    Feeds the contents of a text file WITH A SINGLE PROBLEM to the MCMakeProblem-script.
    :param filecontents:
    :return:
    """
    print(f"\nFile contents:\n"
          f"--------------\n"
          f"{filecontents}\n\n")
    try:
        print("Feeding the contents of a text file to MCMakeProblem...")
        subprocess.run(["./MCMakeProblem"], filecontents, encoding="UTF8")
    except:
        print("... aaaand something went wrong")
        raise


def read_html_for_assignments(htmlfile, suffix=".html"):
    """
    Reads and returns the assignment text and MathCheck-code from a MakeProblem-generated HTML-file.
    :param htmlfile:
    :param suffix:
    :return:
    """
    assignments = re.findall("<tr><td class=ifrl>[\s\S]+?\d+.[\s\S]+?</textarea>", htmlfile)
    assignment = "".join(re.findall(r'\d+\.(?:(?:\s+)?[A-Ö][\s\S]+?[.?])+', assignments))
    mccode = re.findall("verbose_off\s*[\s\S]*?</textarea>", assignment)[0][:-len("\n</textarea>"):]

    return assignment, mccode


def write_txt(contents, destination):
    """
    Writes the given contents to a destination file.
    :param contents:
    :param destination:
    :return:
    """
    with open(destination, "w") as f:
        f.write(contents)
    return


def generate(filename, destination):
    print("\nGenerating a problem...\n")
    # filename = str(filename)
    filecontents = read_txt(filename)
    create_HTML_folder()
    feed_txt_to_MakeProblem(filecontents)  # A html-file is put out by this line
    create_HTML_folder()
    redirect_HTML(f"./{filename}1.html")  # The created html-file is moved to a sub-folder
    assignment, mccode = read_html_for_assignments(f"./HTMLfiles/{filename}1.html")

    write_txt(assignment, f"{destination}/instructions.txt")
    write_txt(mccode, f"{destination}/mccode.txt")
    print("... done.")


testfile = "./TxtFiles/testi.txt"
testdest = "./tehtavat/testi/00/"

print()
print()
filename = testfile  # sys.argv[1]
print(filename)
destination = testdest  # sys.argv[2]
print(destination)
generate(filename, destination)

但是,尝试运行TypeError时,将上面的脚本与所需的文件和目标文件夹一起运行会返回feed_txt_to_MakeProblem

Feeding the contents of a text file to MCMakeProblem...
... aaaand something went wrong
Traceback (most recent call last):
  File "./generator.py", line 111, in <module>
    generate(filename, destination)
  File "./generator.py", line 95, in generate
    feed_txt_to_MakeProblem(filecontents)  # A html-file is put out by this line
  File "./generator.py", line 57, in feed_txt_to_MakeProblem
    subprocess.run(["./MCMakeProblem"], filecontents, encoding="UTF8")
  File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 403, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 609, in __init__
    raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

文本文件的内容格式正确,但是run似乎并不欣赏我试图通过它实现的目标。关于什么可能导致问题的任何想法?

1 个答案:

答案 0 :(得分:0)

这个问题是由我引起的,我忘记了应该将对input=的输入指定为键值对。我忽略了应该在脚本输入之前使用的{{1}}。

对不起我。