如何在不同的目录中执行python脚本?

时间:2017-07-29 01:40:17

标签: python bash python-2.7

已解决请参阅下面的答案,了解可能会对此有所帮助的任何人。

我有两个脚本a.py和b.py. 在我当前的目录“C:\ Users \ MyName \ Desktop \ MAIN”中,我运行> python a.py。

第一个脚本,a.py在我当前的目录中运行,对一堆文件执行某些操作,并使用这些文件的编辑版本创建一个新目录(testA),这些文件同时移动到该新目录中。然后我需要为testA中的文件运行b.py.

作为初学者,我只是将我的b.py脚本复制并粘贴到testA中并再次执行命令“> python b.py”,它会对这些新文件运行一些命令并创建另一个文件夹(testB)那些编辑过的文件。

我试图消除等待a.py完成的麻烦,进入新目录,粘贴b.py,然后运行b.py.我正在尝试编写一个执行这些脚本的bash脚本,同时保持我的目录层次结构。

#!/usr/bin/env bash
 python a.py && python b.py

脚本a.py运行顺利,但b.py根本不执行。没有关于b.py失败的错误消息,我只是认为它无法执行,因为一旦完成a.py,该新目录中就不存在b.py. 我可以在b.py中添加一个小脚本,将其移动到新目录中吗?我实际上也尝试过更改b.py目录路径,但它没有用。

例如在b.py中:

mydir = os.getcwd() # would be the same path as a.py
mydir_new = os.chdir(mydir+"\\testA")

我在b.py中的所有实例中都将mydirs更改为mydir_new,但这也没有区别......我也不知道如何将脚本移动到bash中的新目录中。

作为文件夹的一个小流程图:

MAIN # main folder with unedited files and both a.py and b.py scripts
|
| (execute a.py)
|
--------testA # first folder created with first edits of files
         |
         | (execute b.py)
         |
         --------------testB # final folder created with final edits of files

TLDR:如果b.py依赖于在testA中创建和存储的文件,如何从主测试文件夹(bash脚本样式?)执行a.py和b.py.通常我将b.py复制并粘贴到testA中,然后运行b.py - 但现在我有200多个文件,因此复制和粘贴是浪费时间。

5 个答案:

答案 0 :(得分:5)

最简单的答案可能是更改您的工作目录,然后从第二个.py文件中调用它:

python a.py && cd testA && python ../b.py

当然,您可能会发现编写一个可以为您完成所有操作的脚本更加容易,例如:

将此runTests.sh保存在与a.py相同的目录中:

#!/bin/sh
python a.py
cd testA
python ../b.py

使其可执行:

chmod +x ./runTests.sh

然后您只需输入您的目录并运行它:

./runTests.sh

答案 1 :(得分:3)

我设法让b.py执行并生成我需要的testB文件夹,同时保留在MAIN文件夹中。对于任何可能想知道的人,在我的b.py脚本的开头我会简单地使用mydir = os.getcwd(),它通常是b.py所在的地方。

为了使b.py保持在MAIN中,同时使其在其他目录中的文件上工作,我写道:

mydir = os.getcwd() # would be the MAIN folder
mydir_tmp = mydir + "//testA" # add the testA folder name
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd() # set the main directory again, now it calls testA

现在运行bash脚本有效!

答案 2 :(得分:1)

您的b.py脚本可以将目录名称作为参数。使用:

访问传递给b.py的第一个参数
import sys
dirname = sys.argv[1]

然后使用:

遍历指定目录中的文件
import os
for filename in os.listdir(dirname):
    process(filename)

有关处理文件的更多选项,请参阅glob.globos.walk

答案 3 :(得分:1)

尽管已经有了答案,我仍然写了一个有趣的脚本,它仍然可以在某些方面提供帮助。 我是为python3编写的,所以有必要调整一些小的东西来在v2.x上执行它(例如打印)。

无论如何......代码会创建一个相对于a.py位置的新文件夹,使用代码创建和填充脚本b.py,执行b并显示b&#39的结果和错误。

结果路径结构是: testFolder | -testA | | -a.py | -testB | | -b.py

代码是:

import os, sys, subprocess

def getRelativePathOfNewFolder(folderName):
    return "../" + folderName + "/"

def getAbsolutePathOfNewFolder(folderName):
    # create new folder with absolute path:
    #   get path of current script:
    tmpVar = sys.argv[0]
    #   separate path from last slash and file name:
    tmpVar = tmpVar[:sys.argv[0].rfind("/")]
    #   again to go one folder up in the path, but this time let the slash be:
    tmpVar = tmpVar[:tmpVar.rfind("/")+1]
    #   append name of the folder to be created:
    tmpVar += folderName + "/"

    # for the crazy ones out there, you could also write this like this:
    # tmpVar = sys.argv[0][:sys.argv[0].rfind("/", 0, 
    sys.argv[0].rfind("/")-1)+1] + folderName + "/"
    return tmpVar

if __name__ == "__main__":
    # do stuff here:
    # ...
    # create new folder:
    bDir = getAbsolutePathOfNewFolder("testB")
    os.makedirs(bDir, exist_ok=True) # makedirs can create new nested dirs at once. e.g: "./new1/new2/andSoOn"
    # fill new folder with stuff here:
    # ...
    # create new python file in location bDir with code in it:
    bFilePath = bDir + "b.py"
    with open(bFilePath, "a") as toFill:
        toFill.write("if __name__ == '__main__':")
        toFill.write("\n")
        toFill.write("\tprint('b.py was executed correctly!')")
        toFill.write("\n")
        toFill.write("\t#do other stuff")

    # execute newly created python file
    args = (
        "python",
        bFilePath
    )
    popen = subprocess.Popen(args, stdout=subprocess.PIPE)
    # use next line if the a.py has to wait until the subprocess execution is finished (in this case b.py)
    popen.wait()
    # you can get b.py´s results with this:
    resultOfSubProcess, errorsOfSubProcess = popen.communicate()
    print(str(resultOfSubProcess)) # outputs: b'b.py was executed correctly!\r\n'
    print(str(errorsOfSubProcess)) # outputs: None

    # do other stuff

而不是创建新的代码文件并用代码填充它当然可以简单地复制现有的代码文件,如下所示: How do I copy a file in python?

答案 4 :(得分:0)

在批处理文件中,可以使用Python模块将%PYTHONPATH%变量设置为文件夹。这样,您就不必更改目录或将推送到网络驱动器。我相信你也可以做类似的事情

set "PYTHONPATH=%PYTHONPATH%;c:\the path\to\my folder\which contains my module"

这将添加我认为的路径(仅当您已经在环境变量中设置了%PYTHONPATH%时,此方法才有效)。

如果没有,也可以做

set "PYTHONPATH=c:\the path\to\my folder\which contains my module"

然后,在同一批处理文件中,您可以执行类似的操作

python -m mymodule ...
相关问题