Search code examples
pythonrshinyshiny-servernameerror

Warning: Error in py_run_file_impl: NameError: name '__file__' is not defined


I'm trying to run a python file named tss.py via R in Shiny. I'm successful in running this file. But it is giving me error when I run a python file via user Interface of Shiny. I am getting no error when I run this tss.py in Pycharm. Do anyone know how can I resolve this problem?

Files path:

D:\PycharmProjects\Tasks\applications\tss.py
D:\PycharmProjects\Tasks\server.R

Server.R:

observeEvent(input$action,{
    py_run_file("applications/tss.py")
  })

tss.py:

import os
import sys
sys.path.append(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0])
print("Mayday! Mayday!")

Error:

Warning: Error in py_run_file_impl: NameError: name '__file__' is not defined
  76: <Anonymous>

Please don't mark this question as duplicate. I'm getting this in R not in Python. Do anyone know how can I resolve this?


Solution

  • I don't know why __file__ isn't defined, probably a bug of the launcher. It normally happens when the package is built-in or when the program has been run throught cx_freeze or py2exe, which isn't the case here.

    In your case, a workaround would be to use sys.argv[0] as this value. It works here because it's the main program you're running. With an auxiliary package it wouldn't work (but __file__ maybe would :))

    So I propose to add this to your tss.py file

    import sys # must be done before
    try:
         __file__
    except NameError: 
        __file__ = sys.argv[0]
    

    so if __file__ exists, well, let it be, else define it as the filepath of the script that is running.