为了账号安全,请及时绑定邮箱和手机立即绑定

子流程更改目录

子流程更改目录

犯罪嫌疑人X 2019-10-10 16:40:44
我想在子目录/超级目录中执行脚本(我首先需要在此子目录/超级目录中)。我无法subprocess进入子目录:tducin@localhost:~/Projekty/tests/ve$ pythonPython 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2Type "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_exceptionOSError: [Errno 2] No such file or directoryPython抛出OSError,我不知道为什么。无论
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

要your_command在不同目录中作为子进程运行cwd,请按照@wim的答案中的建议传递参数:


import subprocess


subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)

子进程无法更改其父级的工作目录(通常是)。cd ..使用子进程在子shell进程中运行不会更改父Python脚本的工作目录,即@glglgl的答案中的代码示例错误。cd是内置的shell(不是单独的可执行文件),它只能在同一过程中更改目录。


查看完整回答
反对 回复 2019-10-10
  • 3 回答
  • 0 关注
  • 575 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信