【发布时间】:2018-05-23 15:52:26
【问题描述】:
以下代码取自Saving work after a SIGINT的参考
class Main(object):
def do_stuff(self):
...
def save_work(self):
...
def __init__(self):
try:
self.do_stuff()
except KeyboardInterrupt:
pass # Or print helpful info
self.save_work()
这在没有子进程的情况下工作得很好。
但是,一旦您在 save_work() 中调用子进程,子进程将不会被执行,因为它会收到 SIGINT 信号。
所以,执行
cmd = r"hadoop fs -put '{}' '{}'".format(
src, dest)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
行不通。
有什么解决方法?
【问题讨论】:
-
仅供参考,这是一个非常危险的命令。取出
shell=True并改成subprocess.Popen(['hadoop', 'fs', '-put', src, dest], stdout=subprocess.PIPE, stderr=subprocess.PIPE)会更安全 -
考虑如果有人要求您上传使用
touch $'$(rm -rf ~)\'$(rm -rf ~)\''创建的文件或包含文字反引号的文件会发生什么。 -
如果你真的需要使用
shell=True,然后去掉文字引号,改为使用pipes.quote()(在Python 2中)或shlex.quote()(在Python中3) 生成符合 POSIX 标准的名称转义。cmd = "hadoop fs put {} {}".format(pipes.quote(src), pipes.quote(dest))仍然会因启动不必要的 shell 而产生性能开销,并且由于与环境变量相关的干扰而容易产生副作用,但它的风险比现在要小得多。
标签: python