我對 Python 在傳遞給os.systemUbuntu 18.04 的命令中不轉(zhuǎn)義反斜杠感到困惑(在 CentOS 上運行良好)??紤]這個程序:#!/usr/bin/env pythonimport osimport sysimport subprocessdef get_command(n): return "echo 'Should be %d backslashes: %s'" % (n, "\\" * n)print("")print("Using os.system directly:")print("")for n in range(1, 5): os.system(get_command(n))print("")print("Using subprocess.check_output:")print("")for n in range(1, 5): sys.stdout.write(subprocess.check_output(get_command(n), shell=True).decode('utf-8'))print("")print("Writing the bash code to a script and using os.system on the script:")print("")for n in range(1, 5): with open('/tmp/script.sh', 'w') as f: f.write(get_command(n)) os.system('/bin/bash /tmp/script.sh')當(dāng)我在 Ubuntu 18.04 上運行它時,我得到了這個:Using os.system directly:Should be 1 backslashes: \Should be 2 backslashes: \Should be 3 backslashes: \\Should be 4 backslashes: \\Using subprocess.check_output:Should be 1 backslashes: \Should be 2 backslashes: \Should be 3 backslashes: \\Should be 4 backslashes: \\Writing the bash code to a script and using os.system on the script:Should be 1 backslashes: \Should be 2 backslashes: \\Should be 3 backslashes: \\\Should be 4 backslashes: \\\\請注意,它在應(yīng)該輸出兩個的地方輸出一個反斜杠,在應(yīng)該輸出三個或四個的地方輸出兩個反斜杠!但是,在我的 CentOS 7 機(jī)器上,一切都按預(yù)期工作。在兩臺機(jī)器上,外殼都是/bin/bash. 這是腳本的python2.7調(diào)用的strace輸出,以防萬一:https : //gist.githubusercontent.com/mbautin/a97cfb6f880860f5fe6ce1474b248cfd/raw我想從 Python 調(diào)用 shell 命令的最安全行為是將它們寫入臨時腳本文件!
添加回答
舉報
0/150
提交
取消