如何解决删除文件夹和文件的Python 3.8 subprocess.run命令获取FileNotFoundError:[WinError 2]系统找不到指定的文件
我在Windows 10计算机上使用python 3.8通过pyinstaller通过subprocess.run(command)方法生成EXE文件。 -我是使用子流程的新手- 这部分正在工作
Pyinstaller生成一个* .spec文件,并生成一个我希望在EXE文件创建后删除的文件夹。 我还在删除命令中使用了子进程。
我的逻辑如下:
import os
import subprocess
import sys
import time
file_name = 'Discovery'
# Delete temp files and folders.
print("Deleting temp files...")
time.sleep(5) # Sleep for 5 seconds
folder_to_delete = '{}/build'.format(os.path.abspath(os.getcwd()))
file_to_delete = '{}/{}.spec'.format(os.path.abspath(os.getcwd()),file_name)
if sys.platform == "win32":
delete_folder_command = f'rmdir /F/Q/S {folder_to_delete}'
delete_file_command = f'del {file_to_delete}'
if sys.platform == "darwing":
delete_folder_command = f'rm -r {folder_to_delete}'
delete_file_command = f'rm {file_to_delete}'
subprocess.run(delete_folder_command)
subprocess.run(delete_file_command)
构建文件夹和* .spec文件存在
但是我遇到了以下错误:
FileNotFoundError: [WinError 2] The system cannot find the file specified
tracebak从行开始
subprocess.run(delete_folder_command)
我尝试以各种方式格式化命令,但均未成功。 例如:
folder_to_delete = build
file_to_delete = f'{file_name}.spec'
delete_folder_command = f'rmdir /F/Q/S {folder_to_delete}'
delete_file_command = f'del {file_to_delete}'
subprocess.run('cd {}'.format(os.path.abspath(os.getcwd())
subprocess.run(delete_file_command)
subprocess.run(delete_folder_command)
在最后一种情况下,追溯始于行
subprocess.run('cd {}'.format(os.path.abspath(os.getcwd())
这似乎是os.path.abspath(os.getcwd()
的问题,但我在逻辑中的另一位置使用了它,而格式化文本没有问题。
create_exe_file_command = 'pyinstaller -F -w -i"{}" --add-data="{}/img;." -n"{}" discovery.py'.format(icon_path,os.path.abspath(os.getcwd()),file_name)
也许我是盲人,或者只需要第二双眼睛,但无法弄清楚为什么会出错。 感谢您能指出我正确的方向。
解决方法
您需要做的就是将命令放在列表中。
示例:
在我的情况下,我创建了一个文件夹,在文件夹中创建了一个文件。现在,以下代码将首先删除文件,然后删除文件夹。
import os
import subprocess
folder_to_delete = 'build'
file = 'Discovery.spec'
file_to_delete = f'{folder_to_delete}/{file}'
base_dir = ['cd',os.path.abspath(os.getcwd())]
folder_command = ['rmdir',folder_to_delete]
file_command = ['rm',file_to_delete ]
subprocess.run(base_dir)
subprocess.run(file_command)
subprocess.run(folder_command)
,
rmdir在外壳解释器中实现。为了运行它,您需要通过将shell=True
传递给subprocess.run来告诉您要在shell中运行命令..
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。