【问题标题】:CD to a directory [duplicate]CD到目录[重复]
【发布时间】:2015-12-24 11:03:46
【问题描述】:

我在 tes.py 文件中有以下代码。

#!/usr/bin/python
import os

path = '/tmp'
f_path = os.chdir( path )
f = os.getcwd()
print f
os.system('cd f')

我想在执行 tes.py 文件时进入 /tmp 目录。但我收到以下错误。

[rishb@xxxxxxx ~]$ ./tes.py
/tmp
sh: line 0: cd: f: No such file or directory

有什么方法可以在 python 中实现我的目标?

【问题讨论】:

  • 错误清楚地表明f 没有找到。检查/tmp中是否有f
  • 我想你的意思是:os.system('cd '+f) ?
  • os.chdir() 怎么样?
  • 您在最后一行使用了文字 'f' 而不是变量 f。试试@Leo 所说的。
  • fPython 中的一个变量,所以如果你只是把它放在一个字符串中,肯定它不起作用。字符串永远是字符串是字符串是字符串。

标签: python


【解决方案1】:

使用os.chdir

cd是bash内部命令,改变CURRENT进程的cwd,os.system创建子进程,子进程不能改变python进程的cwd

而且 python 不能改变 bash 的 cwd 谁是它的父级。

您不能使用任何程序更改 bash 的 cwd,除了 bash 的 source 命令

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多