shell 来自python子进程的基本cygwin命令

zfycwa2u  于 2023-03-19  发布在  Shell
关注(0)|答案(3)|浏览(119)

我想从python运行cygwin并执行cygwin命令。
我使用的是Windows,所以我想在cygwin中运行命令,而不是cmd。我使用的是Python 3.6.1。
我只想知道如何运行基本的命令,这样我就可以从那里工作,像ls

  • subprocess.call("E:/cygwin/bin/bash.exe", "ls")(类似于此,但不起作用)
  • 下面是@pstatix建议的解决方案,它使用Popen()。在stdin.write(b 'ls')之后运行stdin.close()会导致/usr/bin/bash: line 1: ls: command not found错误

我能够做到以下几点:

  • 开口天鹅座:subprocess.call("E:/cygwin/bin/bash.exe")
  • (在Windows上运行命令cmd:subprocess.call("dir", shell=True)

在这种格式下可以吗?当我运行下一个python命令时cygwin会自动关闭吗,或者我需要在此之前退出?
我对这个比较陌生。

ni65a41a

ni65a41a1#

from subprocess import Popen, PIPE

p = Popen("E:/cygwin/bin/bash.exe", stdin=PIPE, stdout=PIPE)
p.stdin.write("ls")
p.stdin.close()
out = p.stdout.read()
print (out)
bxjv4tth

bxjv4tth2#

from subprocess import Popen, PIPE, STDOUT

p = Popen(['E:/cygwin/bin/bash.exe', '-c', '. /etc/profile; ls'], 
          stdout=PIPE, stderr=STDOUT)
print(p.communicate()[0]))

这将打开bash,执行-c之后提供的命令并退出。
您需要预先添加. /etc/profile;,因为bash是在非交互模式下启动的,因此没有初始化任何环境变量,您需要自己获取它们。
如果您在用户文件夹中的babun软件上安装了cygwin(像我一样),代码如下所示:

from subprocess import Popen, PIPE, STDOUT
from os.path import expandvars

p = Popen([expandvars('%userprofile%/.babun/cygwin/bin/bash.exe'), '-c', '. /etc/profile; ls'], 
          stdout=PIPE, stderr=STDOUT)
print(p.communicate()[0])
6yjfywim

6yjfywim3#

对我来说,上面提到的解决方案是这样的问题:p.stdin.write(“ls”)追溯(最近调用最后):文件“",第1行,类型错误:需要类似字节的对象,而不是“str”
我用字节格式发送的命令修复了它

from subprocess import Popen, PIPE
    p = Popen(r"C:/cygwin64/bin/bash.exe", stdin=PIPE, stdout=PIPE)
    p.stdin.write(b"ls")
    p.stdin.close()
    out = p.stdout.read()
    print(out)

相关问题