簡體   English   中英

Python:絕對路徑問題

[英]Python: absolute path issue

我有幾個文件存儲在名為controlFiles的文件夾中。 該文件夾的路徑是Users / Desktop / myproject / controlFiles。

我正在嘗試使用以下代碼在python腳本中運行子過程命令:

def codeml(codeml_location, control_location):
    runPath = codeml_location + '/codeml'
    for file in os.listdir(control_location):
        ctlPath = os.path.abspath(file)
        subprocess.call([runPath, ctlPath])

該腳本的功能是運行一個名為codeml的命令行工具,第一個參數是codeml可執行文件的位置,第二個參數是codeml使用的控制文件的文件夾。 當我運行此腳本時,codeml運行但出現錯誤:

error when opening file /Users/Desktop/myproject/subtree.39.tre.ctl
tell me the full path-name of the file? 

我的困惑來自於controlFiles文件夾不在該路徑內的事實,但它仍標識該文件夾內的文件。

為了檢查我是否輸入了正確的control_location參數,我對代碼進行了如下編輯:

def codeml(codeml_location, control_location):
    runPath = codeml_location + '/codeml'
    for file in os.listdir(control_location):
        print os.path.abspath(file)

運行此命令將所有文件打印在controlFiles文件夾中,但再次在路徑中沒有該文件夾。 這是打印輸出的示例:

/Users/Desktop/myproject/subtree.68.tre.ctl
/Users/Desktop/myproject/subtree.69.tre.ctl
/Users/Desktop/myproject/subtree.70.tre.ctl
/Users/Desktop/myproject/subtree.71.tre.ctl

要運行該函數,我的控件位置參數為:

control_location = /Users/Desktop/myproject/controlFiles

最后一點是,我在終端中的工作目錄是/ Users / Desktop / myproject,這是因為這是我的Click項目的位置。 為什么要拾取文件而不是包含它們的文件夾?

os.listdir確實列出了目錄control_location中的文件名,而不是當前工作路徑中的文件名。 因此,您必須將文件名與路徑control_location結合在一起:

for file in os.listdir(control_location):
    ctlPath = os.path.abspath(os.path.join(control_location, file))

在子過程中設置cwd:

 for file in os.listdir(control_location):
    subprocess.call([runPath, file],  cwd=control_location)

listdir只是返回基本名稱,而不是完整路徑。 將cwd設置為文件所在的位置將允許您僅傳遞文件。 如果listdir可以文件control_location,則子進程也應該沒有問題。

我設法使用以下方法解決此問題:

for file in os.listdir(control_location):
        filepath = os.path.dirname(os.path.realpath(file)) 
        subprocess.call([runPath, filepath])

該腳本的功能是運行一個名為codeml的命令行工具,第一個參數是codeml可執行文件的位置,第二個參數是codeml使用的控制文件的文件夾。

如果control_locationcodeml使用的控制文件的文件夾:

import os
import subprocess

def codeml(codeml_location, control_location):
    executable = os.path.join(codeml_location, 'codeml')
    subprocess.check_call([executable, control_location])

您無需在此處調用os.listdir()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM