在 Linux 中执行 PyInstaller 生成的文件时出现 Python 子进程 FILE NOT FOUND 错误

问题描述 投票:0回答:1

我使用 PyInstaller 生成了一个可执行文件,例如,

test
(没有扩展名,因为它是 Linux)并将其存储在一个目录中,例如
data

我有一个Python程序,如下所示:

import subprocess
from pathlib import Path
...
def run_exe():
    try:
        # get current directory
        currdir = Path.cwd()
        datadir = currdir / "data"
        #print(currdir)
        #print(datadir)    
        
        process = subprocess.run(["./test"], shell=False, capture_output=True, text=True, cwd=datadir)
        if(process.stderr): 
            print("stderr:", process.stderr)
            return JSONResponse(content={"success": False}, status_code=400)
        if(process.returncode == 0):
            print(process.stdout)
            return JSONResponse(content={"success": True})
    except OSError as e:
        print(e)
    except subprocess.CalledProcessError as e:
        print(e)    
    except Exception as e:
        print(type(e).__name__)  # Prints the name of the exception class
        print(e)  # Prints the exception message

我尝试过以下方法:

  1. 输入

    subprocess.run(["ls"]
    ,它会显示正确的目录和文件,包括
    test

  2. 放入

    subprocess.run(["ls", -l"]
    ,显示
    test

    中的执行权限
  3. 我尝试移动到父目录并运行。

  4. 我尝试了

    subprocess.run(["test"] ...)
    ,没有./

  5. 我尝试改变

    shell=True
    。仍然报错。

使用 ls 命令(2 和 3)它会打印输出。

我得到的错误是 OSError:

 [Errno 2] No such file or directory: './test'

任何帮助将不胜感激。谢谢

python subprocess pyinstaller
1个回答
0
投票

在 Python 中运行子进程时,无法通过别名(不带 .sh 扩展名)调用脚本。您需要使用其全名和扩展名来调用脚本。这是因为Python打开了一个与主执行环境隔离的新子shell。

© www.soinside.com 2019 - 2024. All rights reserved.