有没有办法设置一个python文件来运行exe?



是否有办法设置一个python文件运行exe不知道确切的位置,但他们在同一文件夹?我想发送一个恶作剧文件给一个朋友,我想让一个python文件运行一个。exe文件没有他知道(该。exe文件是在同一文件夹位置)我想在这个脚本中添加命令:

import random
from tkinter import *
from random import randint
import time
import threading
root = Tk()
root.attributes("-alpha", 0)
root.overrideredirect(1)
root.attributes("-topmost", 1)
def placewindows():
while True:
win = Toplevel(root)
win.geometry("300x60+" + str(randint(0, root.winfo_screenwidth() - 300)) + "+" + str(randint(0, root.winfo_screenheight() - 60)))
win.overrideredirect(1)
Label(win, text="You got hacked", fg="red").place(relx=.38, rely=.3)
win.lift()
win.attributes("-topmost", True)
win.attributes("-topmost", False)
root.lift()
root.attributes("-topmost", True)
root.attributes("-topmost", False)
time.sleep(.05)
threading.Thread(target=placewindows).start()
root.mainloop()

要找出脚本从哪里运行,请检查__file__特殊变量。然后,您可以去掉文件名,并添加您想要运行的任何其他名称:

import pathlib  # Modern path-handling is nice
me = pathlib.Path(__file__)
mydir = me.parent
mysibling = mydir / 'nameofexecutable.exe'
subprocess.run([mysibling])

中间的三行可以是一行到一行:

mysibling = pathlib.Path(__file__).with_name('nameofexecutable.exe')

,如果你喜欢的话(我给出了三行来展示如何一个组件一个组件地轻松地完成它,但是with_name对于这种特定情况确实是更好的解决方案,因为它直接将脚本名称替换为兄弟文件名)。


作为旁注,您在这里的原始代码非常糟糕。GUI程序应该在事件循环中,在单个线程中执行所有GUI工作;在这种情况下,您有意从不同的线程执行GUI的所有操作,而主线程的事件循环除了这些更改所需的绘图更新外什么也不做。没有理由这样做,这样做是危险的(tkinter可以通过在线程之间编组命令来做得很好,并且因为Python的GIL可以防止数据结构损坏,但它更慢;如果你开始从多个线程中绘图,许多GUI工具包就会死掉)。更好的版本应该是:

# All code above this point unchanged, aside from removing import threading
def placewindows():
# Remove loop; the after call at the end gets the same effect
win = Toplevel(root)
win.geometry("300x60+" + str(randint(0, root.winfo_screenwidth() - 300)) + "+" + str(randint(0, root.winfo_screenheight() - 60)))
win.overrideredirect(1)
Label(win, text="You got hacked", fg="red").place(relx=.38, rely=.3)
win.lift()
win.attributes("-topmost", True)
win.attributes("-topmost", False)
root.lift()
root.attributes("-topmost", True)
root.attributes("-topmost", False)
# Schedule the next call 50 ms from now
# Unlike time.sleep(0.05), this doesn't block
# the event loop, so the GUI remains responsive
root.after(50, placewindows)
# No need for a thread, just call directly
placewindows()  # Performs the first GUI update and schedules the next
# The mainloop will finish up any drawing this call requires
# as soon as it launches
root.mainloop()

如果我明白你需要什么,你想要运行的文件。exe在你的文件。py的同一文件夹中。您可以使用os.listdir()来查找文件:

import os
for i in os.listdit():
print(i)

如果知道文件名,则不需要向上执行代码。要运行一个文件,你只需要验证文件名(i),或者如果文件是唯一的。exe文件夹,你可以使用i.find('.exe ')。

找到文件名后(i):

import os
import subprocess
path = os.getcwd()
filepath = (path+i)
p = subprocess.Popen(filepath, shell=True)
stdout, stderr = p.communicate() 

最新更新