我对 Python 在传递给os.systemUbuntu 18.04 的命令中不转义反斜杠感到困惑(在 CentOS 上运行良好)。考虑这个程序:
#!/usr/bin/env python
import os
import sys
import subprocess
def 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')
当我在 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: \\\\
请注意,它在应该输出两个的地方输出一个反斜杠,在应该输出三个或四个的地方输出两个反斜杠!
但是,在我的 CentOS 7 机器上,一切都按预期工作。在两台机器上,外壳都是/bin/bash. 这是脚本的python2.7调用的strace输出,以防万一:https : //gist.githubusercontent.com/mbautin/a97cfb6f880860f5fe6ce1474b248cfd/raw
我想从 Python 调用 shell 命令的最安全行为是将它们写入临时脚本文件!
相关分类