此工作函数将收到一个字典,该字典将继续根据transfer_type值上传或下载文件。但是,当我使用它来执行Local variable might be referenced before assignment
阶段时,我的IDE正在显示警告subprocess.run
。
我的问题是,我是否应该接受在函数(global cmd
)内作为全局变量的消解,或者我应该忽略这个建议?
def scp_transfer(data):
host = data['host']
remote = data['remote']
local = data['local']
transfer_type = data['transfer_type']
if transfer_type == 'download':
cmd = 'scp -qr %s:%s %s' % (host, remote, local)
if transfer_type == 'upload':
cmd = 'scp -qr %s %s:%s' % (local, host, remote)
run = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
try:
run.check_returncode()
except subprocess.CalledProcessError as e:
print(e.output)
else:
print(run.stdout.decode('utf-8'))
答案 0 :(得分:7)
我会避免将其声明为global
。你可以在函数中声明它:
cmd = None
if transfer_type == 'download':
cmd = 'scp -qr %s:%s %s' % (host, remote, local)
if transfer_type == 'upload':
cmd = 'scp -qr %s %s:%s' % (local, host, remote)
当您尝试运行cmd
时,这仍可能导致问题。相反,如果transfer_type
与任何内容都不匹配,则应引发异常。
if transfer_type == 'download':
cmd = 'scp -qr %s:%s %s' % (host, remote, local)
elif transfer_type == 'upload':
cmd = 'scp -qr %s %s:%s' % (local, host, remote)
else:
raise ValueError('Unexpected transfer type: %s' % transfer_type)
无论如何,我总是会注意警告。