os.system 用cd没有作用
时间: 2023-12-16 08:06:33 浏览: 26
`os.system` 是 Python 中用来执行系统命令的方法,它可以执行任何能在终端中执行的命令。但是使用 `cd` 命令时,它只会在子进程中改变当前工作目录,不会影响主进程的当前工作目录。
如果你想在 Python 中改变当前工作目录,可以使用 `os.chdir()` 方法。例如:
```
import os
os.chdir('/path/to/directory')
```
这会将当前工作目录改变为 `/path/to/directory`。注意,在使用 `os.chdir()` 方法时,你需要传递一个有效的路径作为参数,否则会抛出异常。
相关问题
请帮我用python 的os.system模块写一个cd 到某个path
好的,我可以帮你写一个用Python中的os.system模块CD到指定路径的代码。示例代码如下:
```python
import os
path = "/path/to/directory"
cmd = "cd " + path
os.system(cmd)
```
其中,`path`是你想要进入的目录的路径,`cmd`是要执行的命令字符串,使用`os.system()`函数来执行该命令,即可完成目录切换操作。
需要注意的是,使用`os.system()`函数执行系统命令时,需要谨慎考虑命令的安全性,避免因为不当的命令被执行而导致系统安全问题。
import os import time # 获取当前系统时间 curTime = time.strftime("%Y-%m-%d_%H%M", time.localtime()) # 以当前系统时间生成log文件 # open("{}.log".format(curTime),"a", encoding="utf-8") # os.system("cd. > {}.log".format(curTime)) # 获取当前文件夹路径 base_path = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0] file_path= "D:\脚本文件\KM、ORDM回归UI自动化脚本\KM\在线\答案配置\答案编辑" sum = 0 for file_name in os.listdir(file_path): if file_name.find(".air")>0: sum=sum+1 print("当前执行第 {} 个案例, 名称为:{}".format(sum, file_name)) f = open("{}.log".format(curTime),"a+", encoding="utf-8") f.write("当前执行第 {} 个案例, 名称为:{}".format(sum, file_name)) f.write("\n") f.write("--"*20) f.write("\n") f.close() cmd = "airtest run {} >> {}.log".format(file_path+"\\"+file_name, curTime) print("值‘{}’".format(cmd)) # exe_com = os.system(cmd) os.system(cmd) # 执行脚本 time.sleep(3) f = open("{}.log".format(curTime),"a+", encoding="utf-8") f.write("共识别 {} 个脚本".format(sum)) f.close()
你的代码看起来是一个自动化脚本,用于执行某个文件夹下的一系列脚本,并将执行结果写入日志文件中。在代码中,你使用了 `{}.log` 的方式来生成日志文件名,并在循环中打开、写入内容、关闭日志文件。
在你的代码末尾,你再次打开日志文件来写入执行的总结信息,然后关闭文件。
因此,你的代码中已经正确地打开和关闭了日志文件。无需额外操作来关闭文件。