在子过程模块中使用的特殊字符

发布于 2025-02-01 11:55:32 字数 557 浏览 2 评论 0原文

在Python的子过程中,

 subprocess.Popen(
            (
                "git",
                "add",
                "-A",
                "&&",
                "git",
                "commit",
                "-m",
                commit_message
            ),
            cwd=path,
        )

不起作用。 但是,如果我将其分成

 subprocess.Popen(( "git", "add","-A") , cwd=path)

subprocess.Popen(( "git", "commit","-m" , "yeah") , cwd=path)

有效。我如何插入”& amp;''在中间?谢谢。

In subprocess module in python,

 subprocess.Popen(
            (
                "git",
                "add",
                "-A",
                "&&",
                "git",
                "commit",
                "-m",
                commit_message
            ),
            cwd=path,
        )

does not work.
However if I split it into

 subprocess.Popen(( "git", "add","-A") , cwd=path)

and

subprocess.Popen(( "git", "commit","-m" , "yeah") , cwd=path)

it works. How do I insert "&&" in the middle? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等往事风中吹 2025-02-08 11:55:32

&&逻辑运算符是Shell(例如,bash)理解的东西。但是,您正在执行Git,这不了解&&的意思。换句话说,您正在输入参数,就好像您将它们输入到终端一样。 subprocess.popen默认情况下不会调用shell,而是用指定的参数调用exec系统调用。因此,您告诉它运行git带有参数add-a(到目前为止,很好),&amp ;&(git不了解这一点),git-m是的

要执行此操作为shell命令,您需要将shell = true添加到subprocess.popen。这样做后,您可以将想要的命令输入单个字符串:

subprocess.Popen('git add -A && git commit -m', shell=true, cwd=path)

The && logical operator is something that the shell (e.g., bash) understands. However, you're executing git which doesn't understand what && means. Explained another way, you're entering the arguments as if you were typing them into a terminal. subprocess.Popen doesn't invoke the shell by default and instead invokes the exec system call with the specified arguments. So, you're telling it to run git with the arguments add, -A (so far, so good), && (git doesn't understand this), git, -m, and yeah.

To execute this as a shell command, you need to add shell=True to subprocess.Popen. Once you do that, you can just type out the command you want as a single string:

subprocess.Popen('git add -A && git commit -m', shell=true, cwd=path)
青柠芒果 2025-02-08 11:55:32

只有外壳才能Interpet &&,它不是程序或参数,

您可以将shell = true subprocess.popen.popen 运行您的运行在迷你壳中的命令中,请参见在这里文档

Only a shell can interpet &&, it's not program or an argument

You can pass shell=True to subprocess.Popen to run your command in a mini-shell like environment, see docs here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文