简体   繁体   English

if-then bash语句作为Python子进程中的序列

[英]If-then bash statement as a sequence in Python subprocess

Is there any way to execute the if-then bash statement as a sequence in Python subprocess? 有什么方法可以在Python子进程中将if-then bash语句作为序列执行? I can execute the if-then statement as a string, but I want to convert it into a sequence for a safer code. 我可以将if-then语句作为字符串执行,但是我想将其转换为序列以获取更安全的代码。

This is my program at the moment. 这是我目前的程序。 It uses string as the first input of the subprocess with shell=True argument. 它使用string作为带有shell=True参数的子流程的第一个输入。

# this example works
import subprocess
p = subprocess.Popen('if [ ! -d "dir1" ]; then mkdir dir1; fi;', shell=True)

I want to convert the first argument as a sequence with shell=False argument, but I don't know how to make the statement above as a sequence. 我想将第一个参数转换为带有shell=False参数的序列,但是我不知道如何将上述语句作为序列。 This is what I've tried. 这就是我尝试过的。

# this example does not work
import subprocess
p = subprocess.Popen(['if','[ ! -d "dir1" ];','then','mkdir','dir1;','fi;'], shell=False)

if is a shell keyword, not an external command, so you shouldn't use a list argument; if是shell关键字,而不是外部命令,则不应使用列表参数; the string has to be parsed and executed by the shell. 该字符串必须由外壳程序解析和执行。 (You can use shell=True with a list, but it's kind of pointless, since Popen has to concatenate the list items into a single string anyway.) (您可以将shell=True与列表一起使用,但这是毫无意义的,因为Popen必须将列表项串联为单个字符串。)

However, you don't need a shell if statement for this particular example, as the -p option to mkdir will instruct it to only create the directory if it doesn't already exit. 但是,对于此特定示例,您不需要shell if语句,因为mkdir-p选项将指示它仅在目录尚未退出时创建目录。

p = subprocess.Popen(["mkdir", "-p", "dir1"])

Further, you don't need a subprocess at all , because Python provides its own wrapper around the system call that creates a directory. 此外,你并不需要在所有的子进程,因为Python提供围绕创建一个目录系统调用自己的包装。

try:
    os.mkdir("dir1")
except FileExistsError:
    pass

(Catch and ignore the exception rather than checking if the directory exists first to avoid the race condition where someone could create the directory after you check for it but before you actually try to create it.) (捕获并忽略该异常,而不是先检查目录是否存在,以避免出现竞争状况,即有人可以在检查目录之后但在实际尝试创建目录之前创建目录。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM