xiaofeiIDO

python 之 改变工作目录

一、借助os.system()函数

该方法主要是借助Linux的操作系统,os.system()将调用shell,改变工作目录。如果执行成功返回值是0,执行失败返回值是非零数字(如256)

 1 #成功
 2 >>> cd = \'cd \'+ \'box2\'
 3 >>> import  os
 4 >>> n = os.system(cd)
 5 >>> print n
 6 输出 0
 7 #失败
 8 >>> cd = \'cd \'+ \'box3\'
 9 >>> n = os.system(cd)
10 sh: line 0: cd: box3: No such file or directory
11 >>> print n
12 输出 256

二、os模块

该方法调用了python模块中的chdir()函数,即os.chdir(),直接改变了工作目录,无返回值。

 1  #!usr/bin/env python
 2    import os
 3   currentPath = os.getcwd()
 4   b = os.path.join(currentPath, \'box2\')
 5   n = os.chdir(b)
 6   os.system(\'ls\')
 7    print n
 8 #输出
 9 $python chdir.py
10 box2  execbox  __MACOSX  pipeline_description.docx  taskbox
11 None

 

分类:

技术点:

相关文章:

  • 2021-12-31
  • 2022-02-13
  • 2021-12-12
  • 2021-11-29
  • 2021-11-20
  • 2022-12-23
  • 2021-12-03
猜你喜欢
  • 2021-12-26
  • 2021-12-22
  • 2021-11-17
  • 2022-01-21
  • 2021-11-26
  • 2022-12-23
  • 2021-12-02
相关资源
相似解决方案