This working function will receive a dictionary that will proceed with uploading or download files based on the transfer_type value. But currently my IDE is displaying the warning Local variable might be referenced before assignment
when i'm using it to execute the subprocess.run
stage.
My question is, should i accept the sugestion of declating as a global variable inside the function ( global cmd
) or should I ignore this suggestion?
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'))
I would avoid declaring it as a global
. You could declare it within the function:
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)
This could still cause issues when you try to run the cmd
though. Instead, you should raise an exception if transfer_type
doesn't match anything.
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)
In any case, I would always pay attention to the warning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.