以下是 Python 脚本中的相关代码,其中执行一些命令来复制可执行文件,然后执行它:
exe_file_path = os.getcwd() + r'\name_of_executable.exe'
temp_loc = os.environ['temp']
subprocess.Popen(r'copy %s %s' % (exe_file_path, temp_loc), shell=True)
exe_file_path = os.environ['temp'] + r'\name_of_executable.exe'
subprocess.Popen(r'start %s' % (exe_file_path), shell=True)
subprocess.Popen(r'del %s' % (exe_file_path), shell=True)
目前,name_of_executable.exe
仅打印出文本,然后调用 system("暂停”)
。
执行暂停后,我按下 enter
,我会假设可执行文件将关闭并且 Python 脚本将继续,但 Python 的最后一行不会执行。
这是因为我使用的是 TEMP 文件夹吗? (我正在以管理员身份运行命令提示符来执行。如何让脚本工作?
Here is the relevant code from a Python script where a few commands are executed to copy an executable file and then execute it:
exe_file_path = os.getcwd() + r'\name_of_executable.exe'
temp_loc = os.environ['temp']
subprocess.Popen(r'copy %s %s' % (exe_file_path, temp_loc), shell=True)
exe_file_path = os.environ['temp'] + r'\name_of_executable.exe'
subprocess.Popen(r'start %s' % (exe_file_path), shell=True)
subprocess.Popen(r'del %s' % (exe_file_path), shell=True)
Currently, name_of_executable.exe
only prints out text and then calls system("pause")
.
After the pause is executed, I push enter
and I would assume the executable would close and the Python script would continue, but the last line of Python doesn't execute.
Is this because I'm using the TEMP folder? (I'm executing from a command prompt running as administrator. How do I get the script to work?
发布评论
评论(1)
所有程序将立即依次启动。在每个 Popen 对象上调用 communicate 以等待程序终止。
此外,使用格式字符串会产生不必要的危险。
['copy', exe_file_path, temp_loc]
自动转义exe_file_path
和temp_loc
中的任何奇怪字符(并且更易于阅读)。顺便说一下,Python 在 shutil 和 操作系统;无需为此调用 shell 程序。
您应该使用 exe_file_path “nofollow">
os.path.join
(尽管这并不重要,因为您的程序似乎锁定到 Windows)。All programs will be immediately started one after another. Call communicate on each Popen object to wait for program termination.
Additionally, your use of format strings is unnecessarily dangerous.
['copy', exe_file_path, temp_loc]
automatically escapes any strange characters inexe_file_path
andtemp_loc
(and is easier to read).By the way, Python has very good functions for copying and deleting files in shutil and os; there is no need to call shell programs for that.
And instead of concatenating strings to determine
exe_file_path
, you should useos.path.join
(although this is not that important, since your program seems locked to Windows).