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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45384429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:58:08  来源:igfitidea点击:

How to execute a python script in a different directory?

pythonbashpython-2.7

提问by CuriousDude

Solvedsee my answer below for anyone who might find this helpful.

已解决,请参阅下面我的答案,以了解可能对您有帮助的任何人。

I have two scripts a.py and b.py. In my current directory "C:\Users\MyName\Desktop\MAIN", I run > python a.py.

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

The first script, a.py runs in my current directory, does something to a bunch of files and creates a new directory (testA) with the edited versions of those files which are simultaneously moved into that new directory. Then I need to run b.py for the files in testA.

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

As a beginner, I would just copy and paste my b.py script into testA and execute the command again "> python b.py", which runs some commands on those new files and creates another folder (testB) with those edited files.

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

I am trying to eliminate the hassle of waiting for a.py to finish, move into that new directory, paste b.py, and then run b.py. I am trying to write a bash script that executes these scripts while maintaining my hierarchy of directories.

我试图消除等待 a.py 完成的麻烦,移动到那个新目录,粘贴 b.py,然后运行 ​​b.py。我正在尝试编写一个 bash 脚本来执行这些脚本,同时维护我的目录层次结构。

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

Script a.py runs smoothly, but b.py does not execute at all. There are no error messages coming up about b.py failing, I just think it cannot execute because once a.py is done, b.py does not exist in that NEW directory. Is there a small script I can add within b.py that moves it into the new directory? I actually tried changing b.py directory paths as well but it did not work.

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

For example in b.py:

例如在 b.py 中:

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

I changed mydirs to mydir_new in all instances within b.py, but that also made no difference...I also don't know how to move a script into a new directory within bash.

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

As a little flowchart of the folders:

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

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: How do I execute a.py and b.py from the main test folder (bash script style?), if b.py relies on files created and stored in testA. Normally I copy and paste b.py into testA, then run b.py - but now I have 200+ files so copying and pasting is a waste of time.

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

采纳答案by 3D1T0R

The easiest answer is probably to change your working directory, then call the second .pyfile from where it is:

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

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


Of course you might find it even easier to write a script that does it all for you, like so:

当然,您可能会发现编写一个为您完成所有工作的脚本更容易,如下所示:

Save this as runTests.shin the same directory as a.pyis:

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

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

Make it executable:

使其可执行:

chmod +x ./runTests.sh

Then you can simply enter your directory and run it:

然后你可以简单地输入你的目录并运行它:

./runTests.sh

回答by CuriousDude

I managed to get b.py executing and producing the testB folder where I need it to, while remaining in the MAIN folder. For anyone who might wonder, at the beginning of my b.py script I would simply use mydir = os.getcwd() which normally is wherever b.py is.

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

To keep b.py in MAIN while making it work on files in other directories, I wrote this:

为了将 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

Running the bash script now works!

运行 bash 脚本现在可以工作了!

回答by Mark Tolonen

Your b.pyscript could take the name of the directory as a parameter. Access the first parameter passed to b.pywith:

您的b.py脚本可以将目录名称作为参数。访问传递给的第一个参数b.py

import sys
dirname = sys.argv[1]

Then iterate over the files in the named directory with:

然后使用以下命令遍历指定目录中的文件:

import os
for filename in os.listdir(dirname):
    process(filename)

Also see glob.globand os.walkfor more options processing files.

另请参阅glob.globos.walk了解更多选项处理文件。

回答by Philipp Lange

despite there are already answers i still wrote a script out of fun and it still could be of help in some respects. I wrote it for python3, so it is necessary to tweak some minor things to execute it on v2.x (e.g. the prints).

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

Anyways... the code creates a new folder relative to the location of a.py, creates and fills script b.py with code, executes b and displays b's results and errors.

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

The resulting path-structure is: testFolder |-testA | |-a.py |-testB | |-b.py

生成的路径结构是: testFolder |-testA | |-a.p​​y |-testB | |-b.py

The code is:

代码是:

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

instead of creating a new code file and filling it with code you of course can simply copy an existing one as shown here: How do I copy a file in python?

您当然可以简单地复制一个现有的代码文件,而不是创建一个新的代码文件并用代码填充它,如下所示: 如何在 python 中复制文件?