子进程更改目录 [英] Subprocess changing directory

查看:37
本文介绍了子进程更改目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在子目录/超级目录中执行一个脚本(我需要先在这个子目录/超级目录中).我无法让 subprocess 进入我的子目录:

I want to execute a script inside a subdirectory/superdirectory (I need to be inside this sub/super-directory first). I can't get subprocess to enter my subdirectory:

tducin@localhost:~/Projekty/tests/ve$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import os
>>> os.getcwd()
'/home/tducin/Projekty/tests/ve'
>>> subprocess.call(['cd ..'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Python 抛出 OSError,我不知道为什么.无论我是尝试进入现有的子目录还是进入一个目录(如上所述)都没有关系 - 我总是以相同的错误告终.

Python throws OSError and I don't know why. It doesn't matter whether I try to go into an existing subdir or go one directory up (as above) - I always end up with the same error.

推荐答案

你的代码试图做的是调用一个名为 cd .. 的程序.你想要的是调用一个名为 cd 的命令.

What your code tries to do is call a program named cd ... What you want is call a command named cd.

但是 cd 是一个 shell 内部.所以你只能称之为

But cd is a shell internal. So you can only call it as

subprocess.call('cd ..', shell=True) # pointless code! See text below.

但这样做毫无意义.由于没有进程可以更改另一个进程的工作目录(同样,至少在类 UNIX 操作系统上,但在 Windows 上也是如此),因此此调用将具有子shell更改其目录并立即退出.

But it is pointless to do so. As no process can change another process's working directory (again, at least on a UNIX-like OS, but as well on Windows), this call will have the subshell change its dir and exit immediately.

您可以使用 os.chdir() 或使用 subprocess 命名参数 cwd 来实现您想要的,它会立即更改工作目录执行一个子进程.

What you want can be achieved with os.chdir() or with the subprocess named parameter cwd which changes the working directory immediately before executing a subprocess.

比如在根目录下执行ls,你可以这样做

For example, to execute ls in the root directory, you either can do

wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)

或者干脆

subprocess.Popen("ls", cwd="/")

这篇关于子进程更改目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆