[英]bash command not running through python
我有以下方法:
def _run_command(bash_command: str) -> str:
"""
Run a bash command.
Args:
bash_command: command to be executed.
"""
logging.info(f"Running {bash_command}.")
process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if error is not None:
logging.exception(f"Error running command: {bash_command}")
raise ValueError(error)
return str(output)
我用來通過 Python 運行 shell 命令。 除了這種情況外,它似乎適用於大多數情況:
command = f'find {self._prefix} -name "*.txt" -type f -delete'
output = self._run_command(command)
其中self._prefix
是路徑,例如/opt/annotations/
。 我希望此命令刪除該路徑內的所有 txt 文件,但事實並非如此。 但是,如果我直接在終端中運行此命令find /opt/annotations/ -name "*.txt" -type f -delete
,一切都會按預期刪除。 所以我想知道我是否在這里遺漏了什么。
日志記錄顯示了 expect 命令,但是,txts 不會被刪除:
2020-11-18 19:07:47 fm-101 root[10] INFO Running find /opt/annotations/ -name "*.txt" -type f -delete.
問題是引號。 您沒有匹配"*.txt"
文件,但只有匹配*.txt
文件。
將您的命令作為列表顯式傳遞,而不是嘗試從字符串生成列表,以避免出現此問題和其他問題:
def _run_command(command_argv: list) -> str:
logging.info(f"Running {command_argv}.")
process = subprocess.Popen(command_argv, stdout=subprocess.PIPE)
output, error = process.communicate()
if error is not None:
logging.exception(f"Error running command: {bash_command}")
raise ValueError(error)
return str(output)
_run_command(['find', str(self._prefix), '-name', '*.txt', '-type', 'f', '-delete'])
如果您堅持將參數作為字符串,請使用shlex.split()
來獲得對引用值的 POSIX sh-like(不是 bash-like)處理:
def _run_command(shell_command: str) -> str:
"""
Run a shell command, but without actually invoking any shell
Args:
shell_command: command to be executed.
"""
logging.info(f"Running {shell_command}.")
process = subprocess.Popen(shlex.split(shell_command), stdout=subprocess.PIPE)
output, error = process.communicate()
if error is not None:
logging.exception(f"Error running command: {shell_command}")
raise ValueError(error)
return str(output)
...但這只能解決引用刪除的具體問題; 它不會使操作在任何其他方面與 shell 兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.