【问题标题】:Subprocess.call() cwd cannot set from text loaded valueSubprocess.call() cwd 无法从文本加载值设置
【发布时间】:2020-05-14 14:23:57
【问题描述】:

TL;DR

当我从文本文件设置filepath 变量时,subprocess.call(cwd=filepath) 不起作用,但当我使用相同的路径手动设置它时,它起作用。

更多信息

当我使用subprocess.call 时,我使用字符串变量指定命令的cwd。当手动定义字符串时,一切都按应有的方式工作。但是,我想从文本文件中的值加载 cwd 路径。我也确定了那部分,我正在从文本文件中加载正确的值。当cwd=filepathfilepath 设置为从文本文件中加载的字符串值时,我得到NotADirectoryError: [WinError 267] The directory name is invalid. 请记住,如果我手动将变量设置为完全相同的路径,我不会收到此错误。我认为这是某种格式问题,我已经玩弄了它/在互联网上浏览了几天,但还没有找到可行的解决方案。

完整代码

import subprocess # to run the process.
import pathlib #to get the path of the file.

programpath = str(pathlib.WindowsPath(__file__).parent.absolute())
blenderfilepath = 'C:/Program Files/Blender Foundation/Blender 2.81/'
settingsfile = 'settings'

# Load in the variables from settings.
def Load():
    global blenderfilepath
    # # look inside settings file for settings.
    sf = open(programpath + '\\' + settingsfile, 'r')
    for line in sf:
        if 'BPL' in line:
            bfp = line.split('-', maxsplit=1)
            blenderfilepath = str(pathlib.Path(bfp[1]))
            print('Path loaded for Blender: ' + blenderfilepath)

        else:
            print('Using default config...')
            return

    sf.close()
    print('Settings loaded')

# Run next job executes the command to run the next job.
def RunNextJob():
    print('Running next job...')
    print(blenderfilepath)
    currentjob = subprocess.call('blender.exe', cwd=blenderfilepath, shell=True, stdout=subprocess.PIPE)

RunNextJob()

补充信息,谢谢!

最初,我只是将字符串从文件中拉出,没有 pathlib 元素。我试过只使用 pathlib 而不将其转换为字符串。这一点值得一提。

对于其他上下文,“设置”文件是包含一行的一行:

BPL-C:/Program Files/Blender Foundation/Blender 2.81/

通过解析来提取路径。我已验证路径提取正确。

感谢任何帮助。谢谢!

【问题讨论】:

  • 从文本文件中读取的行将被换行符终止。您需要在使用前将其剥离。
  • 感谢您的回复。您的评论使我使用了 .rstring(),它解决了问题。非常感谢!

标签: python python-3.x subprocess blender pathlib


【解决方案1】:

对于遇到同样问题的其他人,请将 .rstring() 添加到字符串的末尾。它会去除字符串中的任何行尾和其他有时不可见的元素。

更新后的行内容如下: blenderfilepath = str(pathlib.Path(bfp[1]).rstring())

感谢jasonharper 的帮助!

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2021-08-09
    • 2020-12-08
    • 2019-02-23
    • 2013-01-29
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多