【问题标题】:Python3 subprocess.Popen is failing to remove file with "FileNotFoundError: [Errno 2] No such file or directory" error, but file is actually presentPython3 subprocess.Popen 无法删除带有“FileNotFoundError: [Errno 2] No such file or directory”错误的文件,但文件实际上存在
【发布时间】: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


【解决方案1】:

以下代码有效:

  1 import subprocess
  2
  3
  4 def execute_shell_command(command_list):
  5     data = subprocess.Popen(command_list, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  6     output = data.communicate()
  7     return output
  8
  9
 10 cmd = ["rm -rf t2*"]
 11 command = cmd[0]
 12 prnt1 = "Executing command: " + command
 13 print(f"{prnt1}")
 14 out2 = execute_shell_command(command)
 15 print(f"output = {out2[0]}")
 16 print(f"error = {out2[1]}")

基本上,按原样编写命令,然后在 subprocess.Popen 中添加一个参数 shell=True

【讨论】:

  • 这个解决方案也没有帮助。不知道为什么!我所做的更改是:cmd = ["rm", "-rf", "t2*"] 错误:FileNotFoundError: [Errno 2] No such file or directory: 'rm-rft2*': 'rm-rft2*'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多