【发布时间】:2021-04-29 10:54:10
【问题描述】:
Python3 subprocess.Popen 无法删除文件并出现“FileNotFoundError: [Errno 2] No such file or directory”错误。 但是直接从 bash 终端执行命令会删除文件。
当前文件夹内容:
tmp]$ ll
total 16
-rw-rw-r--. 1 root root 688 Apr 29 09:28 t1.py
-rw-rw-r--. 1 root root 688 Apr 29 10:41 t2.py
-rw-rw-r--. 1 root root 1052 Apr 29 10:41 t3.py
-rw-rw-r--. 1 root root 364 Apr 29 10:45 t4.py
Python 代码 (t4.py):
1 import subprocess
2
3
4 def execute_shell_command(command_list):
5 data = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
6 output = data.communicate()
7 return output
8
9
10 cmd = ["rm -rf ", "", "t2*"]
11 command = cmd[0] + cmd[1] + cmd[2]
12 prnt1 = "Executing command: " + command
13 print(f"{prnt1}")
14 out2 = execute_shell_command(command)
15
输出:
tmp]$ python3 t4.py
Executing command: rm -rf t2*
Traceback (most recent call last):
File "t4.py", line 14, in <module>
out2 = execute_shell_command(command)
File "t4.py", line 5, in execute_shell_command
data = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'rm -rf t2*': 'rm -rf t2*'
【问题讨论】:
-
使用
cmd = ["rm", "-rf ", "t2*"] -
哦,是的,你是对的,用逗号分隔的每个值都应该是 command_list 中的不同元素!
-
这个解决方案也没有帮助。不知道为什么!我所做的更改是:
cmd = ["rm", "-rf ", "t2*"]错误:FileNotFoundError: [Errno 2] No such file or directory: 'rm-rf t2*': 'rm-rf t2*'
标签: python-3.x subprocess