Python:从命令行运行小型多行脚本

问题描述 投票:0回答:3

我有一堆非常小的python脚本,我想从命令行运行。这是一个这样的例子:

import os
for f in os.listdir():
    if not os.path.isdir(f) and f.endswith('.c'):
        dir=f[:-2]
        os.makedirs(dir)
        os.rename( f, dir + '/' + f  )  

我非常清楚我可以将其保存为python脚本(例如renamer.py)并运行如下脚本:

python renamer.py

但是,在编译库时,我有很多这些小脚本,并且只想将它们连接成一个shell脚本。我只是无法弄清楚语法。我认为shell脚本应该如下所示:

#!/usr/bin/env bash

python -c/
"import os;"/
"for f in os.listdir():;"/
"    if not os.path.isdir(f) and f.endswith('.c'):;"/
"        dir=f[:-2];"/
"        os.makedirs(dir);"/
"        os.rename( f, dir + '/' + f  );"  

但是当我运行这个时,我得到错误:

  File "<string>", line 1
    /
    ^
SyntaxError: invalid syntax
./py_test.sh: line 4: import os;/: No such file or directory
./py_test.sh: line 5: for f in os.listdir():;/: No such file or directory
./py_test.sh: line 6:     if not os.path.isdir(f) and f.endswith('.c'):;/: No such file or directory
./py_test.sh: line 7:         dir=f[:-2];/: No such file or directory
./py_test.sh: line 8:         os.makedirs(dir);/: No such file or directory
./py_test.sh: line 9:         os.rename( f, dir + '/' + f  );: No such file or directory

我在这里错过了什么?

python shell
3个回答
2
投票

最好将它们放在Python模块中,将x.py称为函数,并使用python -c "import x; x.y()"作为调用它们的命令。

然后你就可以放置公共代码了,你就可以打开文件并获得Python语法高亮显示。


0
投票

我在等待它过度思考。

这有效

#!/usr/bin/env bash

python -c "
import os
for f in os.listdir():
    if not os.path.isdir(f) and f.endswith('.c'):
        dir=f[:-2]
        os.makedirs(dir)
        os.rename( f, dir + '/' + f  )  
"

0
投票

我建议你在Python module的某个地方把功能收集到一个合适的PYTHONPATH(根据Dan D的回答)。

不过在shell脚本中调用python -c "import renamer; renamer.rename()",我建议在单个Python脚本中调用函数,完全避免使用shell脚本:

#!/usr/bin/env python3

import renamer
import other_fun

if __name__ == "__main__":
    renamer.rename()
    ...
© www.soinside.com 2019 - 2024. All rights reserved.