简体   繁体   English

使用PyInstaller创建Python可执行文件后,权限被拒绝

[英]Permission denied after using PyInstaller to create Python executable

I've created a little web server using the Bottle framework to serve up one webpage. 我使用Bottle框架创建了一个小的Web服务器来提供一个网页。 This is done by my python script "hello.py". 这是通过我的python脚本“ hello.py”完成的。 From the webpage generated by "hello.py", I'm able to edit the contents of a file called "data.txt". 从“ hello.py”生成的网页中,我可以编辑名为“ data.txt”的文件的内容。 This all works perfectly fine when I run "hello.py" from my terminal (python hello.py). 当我从终端(python hello.py)运行“ hello.py”时,所有这些工作都很好。

But when I create an executable using PyInstaller I run into a problem. 但是,当我使用PyInstaller创建可执行文件时,我遇到了问题。 I'm unable to write to my "data.txt" file. 我无法写入我的“ data.txt”文件。 The error message I get is "Permission denied". 我收到的错误消息是“权限被拒绝”。 Everything else in the executable works except this! 可执行文件中的其他所有内容都可以正常工作!

Prior to creating my executable, I set the "data.txt" permissions to 777. This didn't help. 在创建可执行文件之前,我将“ data.txt”权限设置为777。这没有帮助。 I also tried a potential solution I found here - but no luck. 我也尝试了在这里找到的潜在解决方案-但没有运气。 It looked like this: 它看起来像这样:

def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def fix_ownership(path):
"""Change the owner of the file to SUDO_UID"""

uid = os.environ.get('SUDO_UID')
gid = os.environ.get('SUDO_GID')
if uid is not None:
    os.chown(resource_path(path), int(uid), int(gid))

@post('/data<dataValue>') # or @route('/login')
def data(dataValue):
    thePostRequest = str(request.query_string)
    newPostRequest = string.replace(thePostRequest, '%22', '\"')
    fix_ownership("data.txt")
    with open("data.txt","w") as fo:
      fo.write('data = '+newPostRequest)

    return 

I had high hopes, but that didn't work either. 我寄予厚望,但那也没有用。 Here's my code as it stands now (I'm really new to Python so let me know of any glaring mistakes): 这是我现在的代码(我真的是Python新手,所以让我知道任何明显的错误):

from bottle import route, run, static_file, get, post, request, response, redirect
import os
import string
import sys

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)


@get('/Count<deviceNumber>') # or @route('/login')
def Count(deviceNumber):
    return



def fix_ownership(path):
    """Change the owner of the file to SUDO_UID"""

    uid = os.environ.get('SUDO_UID')
    gid = os.environ.get('SUDO_GID')
    if uid is not None:
        os.chown(resource_path(path), int(uid), int(gid))



@post('/data<dataValue>') # or @route('/login')
def data(dataValue):
    thePostRequest = str(request.query_string)
    newPostRequest = string.replace(thePostRequest, '%22', '\"')
    newPostRequest = newPostRequest.replace('%27', '\'')

# THIS DOES NOT WORK AFTER EXECUTABLE IS CREATED BY PYINSTALLER - PERMISSION DENIED :(
    with open("data.txt","w") as fo:
      fo.write('data = '+newPostRequest)

    return



@get('/ajax<noCache>') # or @route('/login')
def ajax(noCache):
    return

@get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def send_image(filename):
    print "getting image..."
    return static_file(filename, root=resource_path('./'))

@get('/<filename:path>')
def send_static(filename):
    return static_file(filename, root=resource_path('./'))

     #   return static_file(filename, root=os.path.join(sys._MEIPASS, './'))



@route('/formSubmit', method='POST')
def formSubmit():
    redirect("/hello", 303)
    return


@route('/hello')
@route('/hello', method='GET')
def hello():
    return '''

    <!DOCTYPE html>

<html>
    <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 -->


      <script type="text/javascript" src="data.txt"></script>
      <script type="text/javascript" src="myJavascript.js"></script>
      <link rel="stylesheet" type="text/css" href="style.css"></script>


        <title>CANARI JR. | Home</title>



 </head>


<body onload="preparePage()">
<div id="spinner"></div> 

<div id="container">


    <div id="headerDiv">

        <div id="logoDiv"><a href="/" onclick="showHome(); return false;">
         <img src="cLogo.png" alt="Canari Jr. Logo"> 
         </a>
        </div>


        <div id="navDiv">
        <a href="/" onclick="showHome(); return false;"><p id="homeBtn" style="color:black;background-color:white">Home</p></a>
        <a href="/" onclick="showSetup(); return false;"><p id="settingsBtn">Settings</p></a>

        </div>





     </div>



<div id="contentDiv">


</div>


<div id="addDiv" style="text-align:center;display:none;">
<h2>Add New Device</h2>
<form method="POST" id="deviceForm" action="/formSubmit" onsubmit="writeTxt('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P');">


<p style="background-color:#f5f5f5;" id="deviceDropdown">Monitor Type:<select name="" id="deviceList" onchange="loadContentA(this.value)">
  <option value="default">Choose one...</option>
  <option value="temp">Temperature</option>
  <option value="humidity">Humidity</option>
  <option value="analog">Analog</option>
  <option value="digital">Digital</option>
  <option value="counter">Counter</option>
</select></p>


<div id="clearDiv" style="clear:both"></div>
<a href="/" id="cancelBtn" onclick="hideAddDiv(); return false;">Cancel</a>

</form>
</div>


<div id="editDiv" style="display:none">


</div>


<div id="setupDiv" style="display:none">
<h2 style="margin-bottom:35px; border:3px solid #8C8C8C; width:40%; margin:0 auto; padding:10px">Change IP Address</h2>
<form method="POST" onsubmit="submitIP('ipAddress'); return false;">
<p>New IP Address:  <input type="text" name="ipAddress" id="ipAddress"><input type="submit" value="Submit" style="padding:5px 10px 5px 10px">
</p>
<p>Make sure to <span style="color:red">write down this IP Address</span> as you will need it to complete setup.</p><br>
</form>

<h2 style="margin-bottom:35px; border:3px solid #8C8C8C; width:40%; margin:0 auto; padding:10px;margin-top:45px;">Binding Mode</h2>
<p>Binding Mode is currently:</p>
<a href="/" id="bindBtn" onclick="bindOn(); return false;" class="btn">OFF</a>
<p>(Click to change)</p>


</div>



</div>
</body>
</html>


    '''
run(host='0.0.0.0', port=8080, debug=True)

I'm using Mac OSX. 我正在使用Mac OSX。

I figured it out! 我想到了! First, I had to refer to my "data.txt" file using this function: 首先,我必须使用此功能来引用“ data.txt”文件:

def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

I used it like so: 我这样使用它:

theDataFile = resource_path('./data.txt')

Then when I went to write to my file, it worked! 然后,当我去写文件时,它就起作用了! Like this: 像这样:

def data(dataValue):
    thePostRequest = str(request.query_string)
    newPostRequest = string.replace(thePostRequest, '%22', '\"')
    newPostRequest = newPostRequest.replace('%27', '\'')
    newPostRequest = newPostRequest.replace('%20', ' ')
    newPostRequest = newPostRequest.replace('%7B', '{')
    newPostRequest = newPostRequest.replace('%7D', '}')


    print "This is the data value: " + newPostRequest

    theDataFile = resource_path('./data.txt')

    with open(theDataFile,"w") as fo:
      fo.write('data = '+newPostRequest)

    return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用pyinstaller将python脚本转换为可执行文件后,我得到:加载共享库时出错...权限被拒绝 - After converting python script to executable with pyinstaller I get: error while loading shared libraries… Permission denied Errno 13 权限被拒绝 Python(使用 pyinstaller) - Errno 13 Permission denied Python (Using pyinstaller) Heroku-&gt; Python:使用子进程启动可执行文件将获得[权限被拒绝] - Heroku -> Python: Using subprocess to launch an executable gets [Permission Denied] python Pyinstaller IOError: [Errno 13] 权限被拒绝 - python Pyinstaller IOError: [Errno 13] Permission denied pyinstaller权限被拒绝:C:\\ Python \\ Scripts \\ build - pyinstaller permission denied: C:\Python\Scripts\build 使用 pyinstaller 后如何修复 python 可执行文件的图标? - How can I fix icon of python executable after using pyinstaller? 使用 Pyinstaller 后在 Windows 中打开 python 可执行文件时出错 - Error opening python executable in Windows after using Pyinstaller OpenBSD 6.1 Python可执行权限被拒绝 - OpenBSD 6.1 Python Executable Permission denied 使用 Pyinstaller 或 Cython 从 Python 模块创建可执行文件 - Create Executable from a Python module with Pyinstaller or Cython 如何在没有pyinstaller的情况下使用“ ./”创建python可执行文件 - How to create a python executable with “./” without pyinstaller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM