子进程改变目录

2025-01-06 08:32:00
admin
原创
99
摘要:问题描述:我想在子目录/超级目录中执行脚本(我需要先进入这个子目录/超级目录)。我无法subprocess进入我的子目录:tducin@localhost:~/Projekty/tests/ve$ python Python 2.7.4 (default, Sep 26 2013, 03:20:26) [G...

问题描述:

我想在子目录/超级目录中执行脚本(我需要先进入这个子目录/超级目录)。我无法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,但我不知道为什么。无论我尝试进入现有子目录还是进入上一级目录(如上所示),我总是遇到相同的错误。


解决方案 1:

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

但是cd是 shell 内部的。因此你只能这样调用它

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

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

os.chdir()您可以使用或在执行子进程之前立即更改工作目录的subprocess命名参数来实现您想要的效果。cwd

例如,要ls在根目录中执行,您可以执行

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

或者简单地

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

解决方案 2:

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

import subprocess

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

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

解决方案 3:

subprocess.call并且模块中的其他方法subprocess都有一个cwd参数。

此参数决定您想要执行进程的工作目录。

所以你可以做这样的事情:

subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')

查看文档subprocess.popen-constructor

解决方案 4:

您想使用可执行文件的绝对路径,并使用cwdkwargPopen来设置工作目录。请参阅文档。

如果 cwd 不为 None,则子进程的当前目录将在执行前更改为 cwd。请注意,在搜索可执行文件时不会考​​虑此目录,因此您无法指定相对于 cwd 的程序路径。

解决方案 5:

我想这些天你会这么做:

import subprocess

subprocess.run(["pwd"], cwd="sub-dir")

解决方案 6:

基于此答案的另一种选择:https ://stackoverflow.com/a/29269316/451710

这使您可以cd在同一进程中执行多个命令(例如)。

import subprocess

commands = '''
pwd
cd some-directory
pwd
cd another-directory
pwd
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
print(out.decode('utf-8'))

解决方案 7:

只需使用os.chdir

示例:

>>> import os
>>> import subprocess
>>> # Lets Just Say WE want To List The User Folders
>>> os.chdir("/home/")
>>> subprocess.run("ls")
user1 user2 user3 user4

解决方案 8:

如果您想要拥有 cd 功能(假设 shell=True)并且仍然想要根据 Python 脚本更改目录,则此代码将允许“cd”命令发挥作用。

import subprocess
import os

def cd(cmd):
    #cmd is expected to be something like "cd [place]"
    cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
    out = p.stdout.read()
    err = p.stderr.read()
    # read our output
    if out != "":
        print(out)
        os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline 
    if err != "":
        print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
    return

解决方案 9:

如果您需要更改目录,请运行命令并获取 std 输出:

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e
Author: user1<user1@email.com>
Date:   2020-04-23 09:58:49 +0200


相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1579  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1355  
  信创产品在政府采购中的占比分析随着信息技术的飞速发展以及国家对信息安全重视程度的不断提高,信创产业应运而生并迅速崛起。信创,即信息技术应用创新,旨在实现信息技术领域的自主可控,减少对国外技术的依赖,保障国家信息安全。政府采购作为推动信创产业发展的重要力量,其对信创产品的采购占比情况备受关注。这不仅关系到信创产业的发展前...
信创和国产化的区别   8  
  信创,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,摆脱对国外技术的依赖。近年来,国货国用信创发展势头迅猛,在诸多领域取得了显著成果。这一发展趋势对科技创新产生了深远的推动作用,不仅提升了我国在信息技术领域的自主创新能力,还为经济社会的数字化转型提供了坚实支撑。信创推动核心技术突破信创产业的发展促使企业和科研...
信创工作   9  
  信创技术,即信息技术应用创新产业,旨在实现信息技术领域的自主可控与安全可靠。近年来,信创技术发展迅猛,对中小企业产生了深远的影响,带来了诸多不可忽视的价值。在数字化转型的浪潮中,中小企业面临着激烈的市场竞争和复杂多变的环境,信创技术的出现为它们提供了新的发展机遇和支撑。信创技术对中小企业的影响技术架构变革信创技术促使中...
信创国产化   8  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用