You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询将Bash环境变量设置代码转换为Python的正确性

你的Python代码存在几个问题,我帮你修正一下:
  • 环境变量名未加引号:os.environ[file]中的file是环境变量的名称,需要用字符串引号包裹,否则会被当作变量解析,引发未定义错误,应该写成os.environ["file"]。
  • 时间格式化的错误:
    1. Python中strftime不能直接调用,需要先获取当前时间对象,比如用datetime.datetime.now()来生成;
    2. 你用的时间格式%d/%m/%Y, %H:%M:%S和原Bash的%Y%m%d_%H%M%S不匹配,原Bash是年(4位)月日_时分秒的格式,应该改成%Y%m%d_%H%M%S。
  • 文件名格式错误:原Bash里是scrutation_(带下划线),你写成了scrutation,少了下划线,会导致文件名和原逻辑不一致。
  • f-string语法错误:f-string中调用函数需要放在{}内部,而不是[]里。

修正后的代码如下:

import os
from datetime import datetime

directory = "/your/actual/directory/path"  # 替换成实际的目录路径
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.environ["file"] = f"{directory}/scrutation_{timestamp}.log"

或者更简洁的写法:

import os
from datetime import datetime

directory = "/your/actual/directory/path"
os.environ["file"] = f"{directory}/scrutation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

注意:要确保directory变量已经被正确赋值为实际的目录路径,否则会导致路径错误。

内容的提问来源于stack exchange,提问作者answer007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:25:44