Repository: pymedusa/Medusa

Issue:
Medusa not working with pythonw on Windows
Hi,

Today I upgraded to the new 0.3.0 and also upgraded to Python 3.7.2 (from 2.7), but now Meduse won't work using `pythonw` anymore. When I launch via pythonw I see the pythonw process appear and almost immedately shutdown again. Since it's pythonw there is no output, and nothing appears in the application log either. I've tried to debug a bit but I'm stuck. As soon I put in `start.py` the line:

```
sys.stderr = open('stderr.txt', 'a')
```

To try and catch any errors, Medusa actually magically starts working, but the log file remains empty (I've verified I am opening the correct file by actually writing something to it, when I do that my write appears in the log file but still nothing else).

My guess is something in the code tries to access `sys.stderr`, but since that's not available when running with `pythonw` the code breaks and the process exits. However because I'm not a Python developer I don't have any proper tools like step-debugging to find out exactly where it fails :(.


Discussion:
What happens if you try to start it with `python.exe`?
@medariox Sorry looks like I forgot to explictly mention that, but starting with `python.exe` (without any adjustments ofc) works fine. It is specifically when starting with `pythonw.exe` that it immediately exits unless I add that `syslog.stderr = ...` line.
@medariox 
AFAIK, Since `pythonw` doesn't provide a console window, methods like `print` / `sys.stdout.write` / etc. throw an exception.

@SunMar 
Try running Medusa with the `--quiet` (or `-q`) argument.
@sharkykh from what I read ([source](https://stackoverflow.com/questions/24835155/pyw-and-pythonw-does-not-run-under-windows-7)), `print` throws an exception in Python 2.x (though the older Medusa version always ran fine under Python 2.7) but that was fixed in Python 3.x. In Python 3.x you don't get an exception anymore when you use `print()` while running in `pythonw`. I don't know about other functions.

As for `--quiet`, I'm actually already using that (probably because otherwise Medusa would fail to start under Python 2.7), my full startup line is:
```
"C:\Program Files\Python37\pythonw.exe" "X:\Medusa\Medusa\start.py" --nolaunch --quiet --datadir "X:\Medusa\Data" --config "X:\Medusa\Data\config.ini"
```

Where `X:\Medusa\Medusa` is where I have my git clone and checkout, and `X:\Medusa\Data` is where all the data files are kept.

As mentioned before, when either I change `pythonw.exe` to `python.exe`, or if I add `sys.stderr = open('stderr.txt', 'a')` at the top of `start.py` then Medusa starts fine (but `stderr.txt` remains empty).

I have also tried encapsulating the call to `main()` in `start.py` in a `try:` / `except:` and then in the `except:` write something to a log file, but strangely enough it nothing was written to my log file suggesting it never got into the `except:` , so it doesn't look to be an exception, though as I've mentioned before, I'm not a Python developer so I could be doing something wrong there. Basically I've tried applying what's mentioned in [this SO answer](https://stackoverflow.com/questions/33844314/python-script-failing-under-pythonw) both with the logger that's mentioned there (in which case I did see some log lines end up in the file, but not the write from inside the `except:`) and with a simple `open('stderr.txt', 'w')`. I know the `open` is working because if I do something like `log = open('stderr.txt', 'w')` at the top followed by `log.write('starting...')`, I see the `starting...` appear in the file, but any `log.write(...)` inside the `except:` is not written to the file.

That's also why I'm kind of lost on what else I can try. Normally I'd just get out a step debugger and step through the code until I find the place where it's failing, but I don't have that setup for Python. If anyone knows of a quick and easy howto on how I could set that up for Python with minimal effort I don't mind giving that a shot to figure out the root cause.
~~After the initial application load, Medusa starts writing to log files. Have you checked `X:\Medusa\Data\Logs\application.log` for errors? (Or any other log entries)~~
@sharkykh Yes, unfortunately nothing is written to `application.log` (unless I add my workaround and Medusa starts as normal). So the problem appears to be before Meduse writes its first entry to `application.log`.
Well, I changed `start.py` to the code below, and I got this error:
```
Traceback (most recent call last):
  File "C:\Github\Medusa-Dev\start.py", line 9, in <module>
    from medusa.__main__ import main
  File "C:\Github\Medusa-Dev\medusa\__main__.py", line 90, in <module>
    from medusa.server.core import AppWebServer
  File "C:\Github\Medusa-Dev\medusa\server\core.py", line 16, in <module>
    from medusa.server.api.v1.core import ApiHandler
  File "C:\Github\Medusa-Dev\medusa\server\api\v1\core.py", line 33, in <module>
    from medusa import (
  File "C:\Github\Medusa-Dev\medusa\process_tv.py", line 22, in <module>
    from unrar2 import RarFile
  File "C:\Github\Medusa-Dev\lib\unrar2\__init__.py", line 53, in <module>
    from .windows import RarFileImplementation
  File "C:\Github\Medusa-Dev\lib\unrar2\windows.py", line 39, in <module>
    faulthandler.enable()
RuntimeError: sys.stderr is None
```

```py
#!/usr/bin/env python
# -*- coding: utf-8 -*
"""Startup script."""
from __future__ import unicode_literals

import sys

try:
    from medusa.__main__ import main

    if __name__ == '__main__':
        if sys.version_info.major == 3 and sys.version_info.minor < 5:
            print('Medusa supports Python 2 from version 2.7.10 and Python 3 from version 3.5.0, exiting!')
            raise Exception('Incorrect Python version. Shutting down!')
        main()

except Exception as e:
    import traceback
    with open('stderr.txt', 'w') as fh:
        traceback.print_exc(file=fh)
```
And FWIW, just fixing the exception above, allows Medusa to start up...
https://github.com/pymedusa/Medusa/blob/e01912a32739984ac683a846d30352a019665448/lib/unrar2/windows.py#L37-L39
```py
if sys.version_info > (3,3):
    import faulthandler
    with open(os.devnull, 'a+') as fh:
        faulthandler.enable(file=fh)
```

**I'm not 100% sure about this code.** This seems a bit hacky.
@sharkykh Wouldn't it make more sense to just remove the `faulthandler` import at this point?
I never used it and I don't understand its use case.
I just wanted to point out that this seems to be the only issue preventing it from working when using `pythonw`...
@sharkykh I just ran `start.py` with the same try/except as you and I can confirm that I'm getting the same error as you.

Note that this issue is new in 0.3.0, the 0.2.x version worked fine with `pythonw.exe`.
@medariox @sharkykh any idea if this can be solved?

I have to have automatic updates disabled right now, because it appears Meduse does a hard reset when updating, destroying my temporary fix. Then when I update I each time have to manually put the hotfix back to make it start up again.

Resolving patch:
diff --git a/lib/unrar2/windows.py b/lib/unrar2/windows.py
--- a/lib/unrar2/windows.py
+++ b/lib/unrar2/windows.py
@@ -34,7 +34,7 @@
 
 from .rar_exceptions import *
 
-if sys.version_info > (3,3):
+if sys.version_info > (3,3) and sys.stderr is not None:
     import faulthandler
     faulthandler.enable()
 


Test patch: