如何在不同的目录中执行python脚本?
已解决请参阅下面的我的答案,以了解可能对此有所帮助的任何人 我有两个脚本a.py和b.py。 在我当前的目录“C:\Users\MyName\Desktop\MAIN”中,我运行了>pythona.py 第一个脚本a.py在我的当前目录中运行,它对一组文件执行某些操作,并使用这些文件的编辑版本创建一个新目录(testA),这些文件的编辑版本将同时移动到新目录中。然后我需要为testA中的文件运行b.py 作为初学者,我只需将我的b.py脚本复制并粘贴到testA中,然后再次执行命令“>python b.py”,它会在这些新文件上运行一些命令,并使用这些编辑过的文件创建另一个文件夹(testB) 我试图消除等待a.py完成的麻烦,移动到新目录,粘贴b.py,然后运行b.py。我试图编写一个bash脚本,在维护目录层次结构的同时执行这些脚本如何在不同的目录中执行python脚本?,python,bash,python-2.7,Python,Bash,Python 2.7,已解决请参阅下面的我的答案,以了解可能对此有所帮助的任何人 我有两个脚本a.py和b.py。 在我当前的目录“C:\Users\MyName\Desktop\MAIN”中,我运行了>pythona.py 第一个脚本a.py在我的当前目录中运行,它对一组文件执行某些操作,并使用这些文件的编辑版本创建一个新目录(testA),这些文件的编辑版本将同时移动到新目录中。然后我需要为testA中的文件运行b.py 作为初学者,我只需将我的b.py脚本复制并粘贴到testA中,然后再次执行命令“>pytho
#!/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多个文件,所以复制和粘贴是浪费时间。我设法让b.py在需要的地方执行并生成testB文件夹,同时保留在主文件夹中。对于任何想知道的人来说,在我的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脚本现在可以工作了 最简单的答案可能是更改工作目录,然后调用第二个.py
文件:
当然,您可能会发现编写一个脚本来为您完成这一切更加容易,例如: 将其另存为
runTests.sh
,与a.py
is位于同一目录中:
#!/bin/sh
python a.py
cd testA
python ../b.py
使其可执行:
chmod +x ./runTests.sh
然后,您只需输入目录并运行它:
./runTests.sh
您的
b.py
脚本可以将目录名作为参数。使用以下命令访问传递给b.py
的第一个参数:
import sys
dirname = sys.argv[1]
然后使用以下命令迭代命名目录中的文件:
import os
for filename in os.listdir(dirname):
process(filename)
有关处理文件的更多选项,请参见
glob.glob
和os.walk
。尽管已经有了答案,但出于乐趣,我仍然编写了一个脚本,在某些方面可能会有所帮助。
我是为python3编写的,因此有必要调整一些次要的东西,以便在v2.x上执行它(例如打印)
无论如何。。。代码将创建一个相对于a.py位置的新文件夹,使用代码创建并填充脚本b.py,执行b并显示b的结果和错误
生成的路径结构是:
测试文件夹
|-种皮
||a.py
|-测试B
||-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
当然,您不必创建新的代码文件并用代码填充它,而只需复制现有的代码文件,如下所示:
在批处理文件中,可以将%PYTHONPATH%变量设置为包含Python模块的文件夹。这样,您就不必更改目录或对网络驱动器使用pushd to。我相信你也可以这样做
set "PYTHONPATH=%PYTHONPATH%;c:\the path\to\my folder\which contains my module"
python -m mymodule ...
这将附加我相信的路径(只有在环境变量中设置了%PYTHONPATH%时,这才有效)
如果你没有,你也可以这样做
set "PYTHONPATH=c:\the path\to\my folder\which contains my module"
然后,在同一批处理文件中,您可以执行以下操作
set "PYTHONPATH=%PYTHONPATH%;c:\the path\to\my folder\which contains my module"
python -m mymodule ...
使用
访问当前目录上方目录中的模块。模块名称
我现在让b.py在主目录中工作。bash脚本不会执行b.py,但是一旦a.py完成,它就会执行。如果我输入“pythona.py”,那么输入“pythonb.py”就可以了。我不知道为什么“python a.py和python b.py”不能做同样的事情。不管怎样,我最终得到了它,它只是一个愚蠢的打字错误!在bash脚本中使用“pythona.py&pythonb.py”确实有效!对不起,我不太擅长linux,但我正在学习。我首先在cmd窗口中运行chmod命令,然后执行runTests.sh?chmod行让我困惑,因为我以前从未使用过它。我也想尝试一下你的方法(除了我自己的方法,这可能不是最好的,因为它确实需要修改一下b.py脚本)哦,它成功了!chmod是每次都需要键入的还是bash脚本的一部分?chmod
行只运行一次。这告诉系统它是一个可执行文件,并且可以执行它。除非对文件运行了相反的chmod-x
命令,该命令会告诉系统不允许执行它,否则它应该只需要在每个要使其可执行的文件上运行一次。为什么要使用两个正斜杠?窗口上的反斜杠需要另一个转义,但双正斜杠没有意义。请参阅