子流程更改目录

我想在子目录/超级目录中执行脚本(我首先需要在此子目录/超级目录中)。我无法subprocess进入子目录:


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,我不知道为什么。无论


犯罪嫌疑人X
浏览 576回答 3
3回答

慕姐4208626

要your_command在不同目录中作为子进程运行cwd,请按照@wim的答案中的建议传递参数:import subprocesssubprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)子进程无法更改其父级的工作目录(通常是)。cd ..使用子进程在子shell进程中运行不会更改父Python脚本的工作目录,即@glglgl的答案中的代码示例错误。cd是内置的shell(不是单独的可执行文件),它只能在同一过程中更改目录。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python