Home > OS >  Script works on Linux , but not on Windows [flask app]
Script works on Linux , but not on Windows [flask app]

Time:07-28

I am trying to write a script that modifies several LaTeX files from the templates I created and places them in new folders [this script will be used for a flask application ]. I have problems when I use the following code:

 # Write results
     with open(outputname   ".tex", 'w ') as f:
          f.write(filedata)

     # Convert result.tex to result.pdf
     proc = subprocess.Popen(['pdflatex', '-interaction=nonstopmode', outputname '.tex'])
     proc.communicate()

     # Remove unnecessary files
     proc = subprocess.Popen(['del', outputname   '.tex'])
     proc = subprocess.Popen(['del', outputname   '.aux'])
     proc = subprocess.Popen(['del', outputname   '.log'])
     proc = subprocess.Popen(['move', outputname   ".pdf", outputfolder])
     proc.communicate()
     return 

def clean_repo(dir, ext):
    filelist = [ f for f in os.listdir(dir) if f.endswith(ext) ]
    for f in filelist:
        os.remove(os.path.join(dir, f))

It works on lunix except that on windows only one document is modified and generated in PDF, the generated PDF is not moved to the created folder, the .aux, .log and .tex type files are not deleted .

application script :

from flask import Flask, render_template, request, redirect, send_file
from latex import find_occurrences, replace_fields, openTemplate, clean_repo
from werkzeug.utils import secure_filename
from flask_cors import CORS
from datetime import datetime
import os

UPLOAD_FOLDER = './static/model/'  # put the files that will be modified #
OUTPUT_FOLDER_BASE = './static/output/'  # file to Put the result #


templatepath = ''  # variable that will contain the path of the template #
app = Flask(__name__)
cors = CORS(app, resources={r"*": {"origins": "*"}})  # ressources #


@app.route("/", methods=['GET'])  # the paths, get doesn't give data #
def index()

    # Render simple page to upload template
    return render_template("index.html")


@app.route("/", methods=['POST'])
def upload():
    # Remove old file (Uploaded templates and output results)
    clean_repo(UPLOAD_FOLDER, ".tex")
    clean_repo(OUTPUT_FOLDER_BASE, ".pdf")

    # Save templates to uploads
    files = request.files.getlist("file")  # select multiple files #

    # If two files have the same name return error (Every template should have a unique name to avoid output folders with the same name)
    if len(files) != len(set(files)):  # command to find a unique file #
        return render_template("index.html", error_message="Certains modèles portent le même nom, renommez-les puis réessayez.")

    for file in files:
        file_name = secure_filename(
            file.filename)  # be sure of the security of the files must not contain a special character or sequence of characters like cd:  which can influence the code #

        template_path = os.path.join(UPLOAD_FOLDER, file_name)
        file.save(template_path)  # operating system =os, provides functions for interacting with the operating system#

    # Redirect to editor
    return redirect("/editor")  # go to page 2 to change the information #


@app.route("/editor", methods=['GET'])
def editor():
    all_occurrences = []  # variable that gets all unique occurrences#

    for template_name in os.listdir(UPLOAD_FOLDER) # list all files found in a path#

        # Load the template in the variable "filedata"
        file_data = openTemplate(os.path.join(UPLOAD_FOLDER, template_name))  # the fields defined in latex #
        # Find the fields to change in the given template
        file_occurrences = find_occurrences(file_data)

        # Add current file occurences to global list
        all_occurrences.extend(file_occurrences)

    # Remove repeated occurrences
    unique_occurrences = list(set(all_occurrences))

    return render_template("index.html", occurrences=unique_occurrences,
                           templateChoosed=True)  # pass contents to the htm page#


@app.route("/editor", methods=['POST'])  # send modification info #
def generate():
    # Extract data from request
    entries = request.form  # variable that contains the values of the fields #

    for template_name in os.listdir(UPLOAD_FOLDER)  # list all files found in a path to get the names #

        file_data = openTemplate(os.path.join(UPLOAD_FOLDER, template_name))

        # datetime object containing current date and time when executed
        now = datetime.now()  # generate a time value #

        # You can change the output folder name as you want, you might remove the time from the folder name by deleting "_%H-%M-%S" bellow for example.
        formatted_datetime = now.strftime("%d-%m-%y_%H-%M-%S")
        # formatting the shape of time  d=day,m=month,y=year,H=hour,M=min ,S= second #

        # Final folder name (ffn)
        ffn = formatted_datetime   "_"   template_name

        # Output folder
        output_folder = os.path.join(OUTPUT_FOLDER_BASE, ffn)
        # new route for results files #

        # Check if folder exists and create new one
        if (os.path.isdir(output_folder)):
            return "<p>[E]: Abort, folder already exists</p>"
        os.mkdir(output_folder)

        ### End of newly added ###

        replace_fields(entries=les
        données, file_data   , template_name= n, output_folder)  # output_folder = chemin  , file_data = contenue de fichier  .tex #

    return render_template("index.html", success_message="Vos fichiers ont été bien générés.")

CodePudding user response:

 proc = subprocess.Popen(['del', outputname   '.tex'])
 proc = subprocess.Popen(['del', outputname   '.aux'])
 proc = subprocess.Popen(['del', outputname   '.log'])
 proc = subprocess.Popen(['move', outputname   ".pdf", outputfolder])

This piece relies on availability of certain command, to avoid that use following functions

these are inside standard library, so you do not need to install anything just add import os and import shutil to use them.

  • Related