[英]Using variable in subprocess command (Python)
當前通話:
f = open('/tmp/list.txt','w')
f.write(list)
f.close() # Make sure to close the file before call sub-process.
# Otherwise, file content will not visible to sub-process.
process = subprocess.Popen('oscommand --file={}'.format(f.name),
shell=True, stdout=subprocess.PIPE)
但是需要使用變量作為已使用[ShortId] [1]生成的參數。 需要類似的東西:
u=ShortId()
process = subprocess.Popen('oscommand --label "The unique id is "'+u' --file={}'.format(f.name),
shell=True, stdout=subprocess.PIPE)
如何最好地進行轉義?
如果您停止嘗試使用shell=True
str
命令,而僅使用更安全,更快的基於shell=False
基於list
的命令(默認),則實際上會更容易:
u=ShortId()
cmd = ['oscommand', '--label', 'The unique id is {}'.format(u), '--file={}'.format(f.name)]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
這避免了包含外殼元字符(例如空格)的id或文件名導致錯誤地解析命令的風險(如果該字符串是主動惡意的,則可能是危險的,例如,名為foo;sudo rm -rf /*
的文件) foo;sudo rm -rf /*
)。
還要注意,有更好的方法來處理臨時文件,無論該文件在Popen
命令完成后是否應持續使用:
import tempfile
with tempfile.NamedTemporaryFile('w+t', delete=False) as f:
f.write(mylist)
... rest of code here ...
或者,如果使用后應自動清除文件:
with tempfile.NamedTemporaryFile('w+t') as f:
f.write(mylist)
f.flush()
... rest of code using temp file ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.