我已经使用 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
我有尝试了以下操作:
-
放置
subprocess.run(["ls"]
,它显示了正确的目录和文件,包括test
-
放置
subprocess.run(["ls", -l"]
,它显示了执行权限test
-
我尝试移动到父目录并运行。
-
我尝试过
subprocess.run(["test"] ...)
没有./ -
我尝试过改变
shell=True
仍然给出错误。
使用 ls 命令(2 和 3)它会打印输出。
我得到的错误是 OSError:
[Errno 2] No such file or directory: './test'
任何帮助将不胜感激。谢谢
遇到的问题在于 PyInstaller 可执行文件在运行时找不到其依赖项。虽然可执行文件本身位于“data”目录中,但它可能需要访问存储在其他位置的文件(例如,在构建可执行文件时所在的原始文件系统位置)。
为了解决这个问题,可以尝试以下几种方法:
1. 使用
--onefile
选项:
使用
--onefile
选项构建 PyInstaller 可执行文件。这会将所有依赖项打包到一个可执行文件中,使其更易于移植。
bash
pyinstaller --onefile your_script.py
2. 指定依赖项路径:
在构建 PyInstaller 可ecutable 文件时,使用
--paths
选项指定依赖项的搜索路径。例如,如果的依赖项位于
/path/to/dependencies
目录中,则可以使用以下命令:
bash
pyinstaller --paths=/path/to/dependencies your_script.py
3. 修改环境变量:
在运行 PyInstaller 可执行文件之前,设置
LD_LIBRARY_PATH
环境变量,使其包含依赖项所在的目录。例如,在 Linux 上,可以使用以下命令:
bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/dependencies
./test
4. 在 Docker 中复制依赖项:
将 PyInstaller 可执行文件所需的 所有 依赖项复制到 Docker 镜像中的“data”目录或子目录中。这将确保可执行文件可以在 Docker 环境中找到其所需的所有文件。
5. 使用绝对路径:
如果知道可执行文件的绝对路径,则可以在
subprocess.run()
调用中使用它。例如:
python
process = subprocess.run(["/absolute/path/to/test"], shell=False, capture_output=True, text=True)
请尝试以上方法,并根据的具体情况选择最合适的一种。如果仍然遇到问题,请提供更多信息,例如:
- 使用的 PyInstaller 版本
- 的操作系统的版本
- 尝试运行的完整命令
- 的 Dockerfile 的内容
这将有助于我们更好地理解的问题并提供更准确的帮助.
标签:python,subprocess,pyinstaller From: 78783045