Cur*_*ude 7 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
Run Code Online (Sandbox Code Playgroud)
脚本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")
Run Code Online (Sandbox Code Playgroud)
我在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
Run Code Online (Sandbox Code Playgroud)
TLDR:如果b.py依赖于在testA中创建和存储的文件,如何从主测试文件夹(bash脚本样式?)执行a.py和b.py. 通常我将b.py复制并粘贴到testA中,然后运行b.py - 但现在我有200多个文件,因此复制和粘贴是浪费时间.
我设法让 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
Run Code Online (Sandbox Code Playgroud)
运行 bash 脚本现在可以工作了!
.py
文件调用它:python a.py && cd testA && python ../b.py
Run Code Online (Sandbox Code Playgroud)
将其保存runTests.sh
在与以下目录相同的目录a.py
中:
#!/bin/sh
python a.py
cd testA
python ../b.py
Run Code Online (Sandbox Code Playgroud)
使其可执行:
chmod +x ./runTests.sh
Run Code Online (Sandbox Code Playgroud)
然后您只需输入您的目录并运行它:
./runTests.sh
Run Code Online (Sandbox Code Playgroud)