如何从 python 运行 exe 文件?

How to run exe file from python?

我尝试从本地 python 项目的特定路径 运行 一个 exe(在后台),使用 os.system 库。 我已经设法更改文件夹,如 'cd' 命令,但我不能 运行 文件。

这是 python 项目 运行ning 在 Windows 64BIT,Python 3.5.3

file.exe 位于 "programs" 目录。

import os
os.system("cd C:\Users\User\AppData\Windows\Start Menu\Programs")
subprocess.Popen("file.exe")

错误:

{OSError}[WinError 193] %1 is not a valid Win32 application

我看到了关于这个问题的其他帖子,但我无法解决它。 有什么想法吗?

你能看看这是否有效

   import os 

    # change the current directory 
    # to specified directory 
    os.chdir(r"C:\Users\User\AppData\Windows\Start Menu\Programs") 
    subprocess.Popen("file.exe")

问题是 system 命令不起作用。它 "works",但在一个立即退出的单独子进程中。当前目录不会传播到调用进程(另外,由于您没有检查 return 代码,即使目录不存在,命令也不会失败。请注意,它发生在这里,如目录名称中有空格并且没有被引用...)。

你必须为此使用 os.chdir,但你甚至不需要它。

如果你想 运行 特定位置的命令,只需传递命令的绝对路径(并且由于它使用字符串文字,请始终使用 r 前缀以避免某些 \t\n 字符被解释为特殊字符...)。例如 python 3,如果命令行出现错误(但在 python 2 中没问题...):

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-6: truncated \UXXXXXXXX escape

所以总是使用原始前缀。以下是我将如何重写:

current_dir = r"C:\Users\User\AppData\Windows\Start Menu\Programs"
subprocess.Popen(os.path.join(current_dir,"file.exe"))

如果您确实需要当前目录与exe 相同,请使用cwd 参数。还获取 Popen 的 return 值,以便能够 wait/poll/kill/whatever 并获取命令退出代码:

p = subprocess.Popen(os.path.join(current_dir,"file.exe"),cwd=current_dir)
# ...
return_code = p.wait()

作为旁注,请注意:

p = subprocess.Popen("file.exe",cwd=current_dir)

不起作用,即使 file.execurrent_dir 中(除非您设置 shell=True,但出于 security/portability 的原因最好避免这样做)

请注意,os.system 已被弃用,原因有很多(好的)。使用 subprocess 模块,always,如果有参数,总是带有参数 list(不是字符串),避免 shell=True 尽可能多。

问题已解决。 谢谢大家,问题是管理权限。以管理员身份启动 pycharm。 就像我说的那样 - 我能够看到带有 os.listdir() 的文件,但是当我尝试 运行 它时,错误开始弹出。 我认为主要问题是 os.system() 从 python 进程继承当前权限。