简体   繁体   English

在子过程命令中使用变量(Python)

[英]Using variable in subprocess command (Python)

Currently calling: 当前通话:

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)

However need to use a variable as an argument which has been generated using [ShortId][1]. 但是需要使用变量作为已使用[ShortId] [1]生成的参数。 Need something like: 需要类似的东西:

u=ShortId()
process = subprocess.Popen('oscommand --label "The unique id is "'+u' --file={}'.format(f.name),
                               shell=True, stdout=subprocess.PIPE)

How is the escaping best handled ? 如何最好地进行转义?

This is actually easier if you stop trying to make str commands with shell=True and just use the safer, faster list based command with shell=False (the default): 如果您停止尝试使用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)

This avoids the risk of either the id or the file name containing shell metacharacters (say, a space) causing the command to be parsed incorrectly (or dangerously, if the string is actively malicious, eg a file named foo;sudo rm -rf /* ). 这避免了包含外壳元字符(例如空格)的id或文件名导致错误地解析命令的风险(如果该字符串是主动恶意的,则可能是危险的,例如,名为foo;sudo rm -rf /*的文件) foo;sudo rm -rf /* )。

Also note that there are better ways to do temporary files, whether or not the file is supposed to last after the Popen command finishes: 还要注意,有更好的方法来处理临时文件,无论该文件在Popen命令完成后是否应持续使用:

import tempfile

with tempfile.NamedTemporaryFile('w+t', delete=False) as f:
    f.write(mylist)
... rest of code here ...

Alternatively, if the file should be cleaned up automatically after use: 或者,如果使用后应自动清除文件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM