我有一個函式將命令作為字串接收,并使用aws二進制檔案在 AWS 容器上運行它。
該命令在用戶請求運行的命令之前和之后添加了一些額外的符號——我不會解釋原因。
def run_command_on_aws_container(command: str, aws_info):
full_command = f"bash -c 'echo -n \"|\"; {command}; echo -n \"|\"'"
subprocess.run(["aws", ..., "--command", full_command], ...)
...
command_to_run_on_aws_machine = 'python -c "for i in range(10): print(i)"'
run_command_on_aws_container(command_to_run_on_aws_machine, aws_info)
這有效,但前提是我的command_to_run_on_aws_machine不包含單引號。如果我command_to_run_on_aws_machine是這樣的,例如:
command_to_run_on_aws_machine = "python -c 'for i in range(10): print(i)'"
這是完全相同的命令,但是使用單引號而不是雙引號,整個事情都會崩潰。或者至少它沒有達到你的預期。
有沒有辦法讓我的run_command_on_aws_container函式同時處理兩個字串,這樣只要commandarg 是正確的 bash 命令,它就會運行?理想情況下,不僅僅是盲目地將字串中的所有單引號轉換為雙引號,而且如果命令包含正確轉義的引號,它仍然可以作業嗎?
run_command_on_aws_container注意:所有作為arg發送的命令都command被硬編碼到程式中。這里沒有在遠程系統上執行任意命令的安全問題。這只是為了方便,所以在函式之外撰寫的代碼不需要擔心如何正確使用字串。
uj5u.com熱心網友回復:
shlex.quote()專門為此設計:
full_command = "bash -c " shlex.quote(f'echo -n "|"; {command}; echo -n "|"')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527935.html
標籤:Python重击
上一篇:使用bash決議和修改csv
