问题描述
我尝试在 python 中使用 open() 打开并读取文件,在 Linux 中使用全局变量 $USER,但程序在第 2 行停止。我想相信问题出在 open() 函数中,因为我在 1 行中使用了 $USER 并且一切正常:
os.system("/usr/bin/nmap {target} -oN /home/$USER/.nmap_diff/scan{today}.txt")
scantxt = open("/home/$USER/.nmap_diff/scan{today}.txt","rb")
输出为:
File "diffscanner.py",line 92,in scanner
scantxt = open("/home/$USER/.nmap_diff/scan{}.txt".format(today),"rb")
FileNotFoundError: [Errno 2] No such file or directory: '/home/$USER/.nmap_diff/scan2021-07-10.txt'
输出说没有找到scan2021-07-10.txt,但确实存在: scan2021-07-10.txt
解决方法
os.system
在 subshell 中执行命令(作为字符串传递)。这意味着,该命令可以访问 Linux 的环境变量,在您的情况下为 USER
。
另一方面,open
需要一个 path-like 对象,例如路径字符串。字符串按原样读取,不会被评估以用实际值替换 USER
(或任何其他环境变量)。如果要使用 env var,请使用 os.environ
import os
USER = os.environ['USER']
scantxt = open(f"/home/{USER}/.nmap_diff/scan{today}.txt","rb")
,
问题是 def train_model(model,criterion,optimizer,scheduler,num_epochs=25):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch,num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train','val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs,labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_,preds = torch.max(outputs,1)
loss = criterion(outputs,labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase,epoch_loss,epoch_acc))
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60,time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
被 $USER
解释为文字字符串,而不是环境变量。要扩展字符串中的环境变量,请使用 os.path.expandvars。
open
顺便说一下,您问题中的字符串看起来也应该是 f-strings,但缺少 os.system(f"/usr/bin/nmap {target} -oN /home/$USER/.nmap_diff/scan{today}.txt")
result_path = os.path.expandvars(f"/home/$USER/.nmap_diff/scan{today}.txt")
with open(result_path,"r",encoding="utf-8") as f:
scantxt = f.read()
前缀。我已将它们添加到我的答案中。
此外,我假设您希望将扫描结果作为字符串,因此我也为此添加了代码。 (似乎 nmap 通常不会在其 f
选项的输出中包含任何非 ascii 字符,但我将编码指定为 UTF-8,以防将来添加对 UTF-8 字符的支持版本。)