【问题标题】:Keep Python Command window open on Windows在 Windows 上保持 Python 命令窗口打开
【发布时间】:2016-12-23 18:56:16
【问题描述】:

好的,我知道这个问题已经被问/回答了很多次,但解决方案在我的情况下不起作用。我在 Raspberry Pi 上的无头 linux 终端上使用 2.7 创建了一个 Python 脚本,它在该环境中完美运行。
该脚本包含一个 sqlite3 数据库。在我的 Windows 10 机器上,如果我只是从 Desktop 中双击 Python 脚本,它会创建 database.db 文件,但 Python 命令提示符在我看到输出之前关闭。

在 Windows 命令提示符下运行 Python 脚本,例如 'start C:\Users\User\Desktop\script.py' 执行完全相同的操作

使用 Run 和 'cmd /k C:\Users\User\Desktop\script.py' 确实使命令窗口持续存在,但随后在打开 sqlite3 数据库的行上出错:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\script.py", line 91, in <module>
    conn = sqlite3.connect("database.db")
sqlite3.OperationalError: unable to open database file

我在 Windows 上的原因是我试图用 Tkinter 构建一个 GUI,而我的 R Pi 没有 GUI,感谢帮助

【问题讨论】:

  • 您不需要cmd /kstart。只需在命令提示符下运行C:\Users\User\Desktop\script.py
  • 好的,谢谢,我已经习惯了 Linux 命令行并且无法适应 Windows
  • 实际上它不起作用,Python Script 使用此方法无法正确执行,如果缺少 database.db 用户必须输入创建数据库,使用上述方法不会出现这种情况跨度>
  • 不应该这样。在程序开头添加input(os.getpid()) 以打印PID 并使其等待。然后在Process Explorer 中,检查进程属性中的“图像”选项卡中的路径、命令行和当前目录。不使用start 会发生什么变化?
  • 我终于想通了,我必须在 PATH 中添加 Python 作为路径,现在只需使用 C:\Users\User\Desktop\script.py

标签: python windows


【解决方案1】:

您需要传递完整路径,例如C:\Users\User\Desktop\database.db

原因是从 'cmd /k C:\Users\User\Desktop\script.py' 运行时,调用该命令的工作目录不同,它会尝试在该文件夹中查找 database.db,并且给你错误。

您可以通过以下方式查看当前dir 是什么:

import os
print os.getcwd()

【讨论】:

  • 如果database.db在脚本目录下,可以使用path = os.path.join(os.path.dirname(__file__), 'database.db'),也可以使用sys.argv[0]代替__file__。后者应该在冻结的可执行文件中工作,例如来自 py2exe 或 pyinstaller。
  • 如果 database.db 丢失,python 脚本将请求用户输入,如果在执行 python 脚本的目录中找不到数据库,则创建数据库。如果我双击 script.py 但我看不到输出,这将非常有效。 database.db 创建/检测的所有这些其他方法都不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多