Search code examples
pythondjangodjango-rest-frameworklibreofficedoc

Subprocess in Django 2.1.7


So, my problem is pretty straight forward I want to execute the following shell command in Django 2.1.7

 libreoffice --headless --convert-to "txt:Text (encoded):UTF8" test.doc 

More info.

I will be uploading a Doc file and want to convert it to txt. I was thinking if i could use the libreoffice to do so. My server is Ubuntu 18.04 with Python 3.6.7 I would be uploading the file in Media Root for now and then i would like to start the conversion. Up till now I have tried to do the following:

@api_view(['POST'])
def convertfiledoc(request):
    file = request.FILES['file']
    fs = FileSystemStorage()
    filename = fs.save(file.name, file)
    uploaded_file_url = 'media/'
    r = subprocess.call("libreoffice --headless --convert-to" +"txt:Text (encoded):UTF8" + "test.doc ")
    print(r)
    return Response(data={"message": uploaded_file_url}, status=status.HTTP_200_OK)

Error is as follows

FileNotFoundError: [Errno 2] No such file or directory: 'libreoffice --headless --convert-totxt:Text (encoded):UTF8test.doc ': 'libreoffice --headless --convert-totxt:Text (encoded):UTF8test.doc '

I know that the function I have written is not complete but I was trying to do it to see if it works properly.

I even tried to hardcode the file but no success.


Solution

  • This worked for me

    command=['libreoffice','--headless','--convert-to','txt:Text (encoded):UTF8','--outdir','test_dir','source_file.docx'] 
    process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)