Python 中的 UNIX 命令链

Chain of UNIX commands within Python

我想在 Python 中执行以下 UNIX 命令:

cd 2017-02-10; pwd; echo missing > 123.txt

日期目录 DATE = 2017-02-10OUT = 123.txt 已经是 Python 中的变量,所以我尝试了

的变体

call("cd", DATE, "; pwd; echo missing > ", OUT)

使用 subprocess.call 函数,但我正在努力同时查找多个 UNIX 命令的文档,这些命令通常由 ; 分隔或用 >[=18 管道分隔=]

在 Python 中的单独行上执行命令也不起作用,因为它“忘记”了上一行执行的内容并且本质重置。

您可以将 shell 脚本作为单个参数传递,并将字符串替换为带外参数,如下所示:

date='2017-02-10'
out='123.txt'

subprocess.call(
  ['cd ""; pwd; echo missing >""',  # shell script to run
   '_',                                 # [=10=] for that script
   date,                                #  for that script
   out,                                 #  for that script
  ], shell=True)

这比将 dateout 值替换为由 shell 作为代码评估的字符串要安全得多,因为这些值被视为文字:A date of $(rm -rf ~) 实际上不会尝试删除您的主目录。 :)

>>> date = "2017-02-10"
>>> command = "cd " + date + "; pwd; echo missing > 123.txt"
>>> import os
>>> os.system(command)

Doing the commands on separate lines in Python doesn’t work either because it “forgets” what was executed on the previous line and essentiality resets.

这是因为如果您单独调用 subprocess.call,它将 运行 每个命令在其自己的 shell 中,而 cd 调用对后来 shells.

解决此问题的一种方法是在执行其余操作之前更改 Python 脚本本身中的目录。这是否是一个好主意取决于脚本其余部分的作用。您真的需要更改目录吗?为什么不直接从 Python 写 "missing" 到 2017-02-10/123.txt?为什么需要 pwd 电话?

假设您正在遍历目录列表并希望输出每个目录的完整路径并创建其中包含 "missing" 的文件,您或许可以这样做:

import os

base = "/path/to/parent"
for DATE, OUT in [["2017-02-10", "123.txt"], ["2017-02-11", "456.txt"]]:
    date_dir = os.path.join(base, DATE)
    print(date_dir)
    out_path = os.path.join(date_dir, OUT)
    out = open(out_path, "w")
    out.write("missing\n")
    out.flush()
    out.close()

如果您没有写入文件的权限或目录不存在,上面可以使用一些错误处理,但您的 shell 命令也没有任何错误处理。