【问题标题】:Cant connect ubuntu terminal and python script无法连接ubuntu终端和python脚本
【发布时间】:2019-04-25 09:01:33
【问题描述】:

我正在尝试通过 python 脚本使用 ubuntu 终端。

脚本接收命令文本(来自 input() 用于测试),将其发送到终端,终端返回命令结果,脚本在控制台中打印结果。

我已经知道我应该使用子进程 Popen 和 PIPE,但是在输入第一个命令后,脚本只打印 b'',在第二个引发错误“ValueError:启动通信后无法发送输入”

我的测试代码(是的,它很糟糕):

import subprocess as sb
from subprocess import PIPE, Popen

p=Popen(['gnome-terminal'],stdout=PIPE,stdin=PIPE,stderr=PIPE)

command = 'cmd'
while True:
    command = input()
    out_data, err_data = p.communicate(command.encode())
    print(repr(out_data))

我知道我做错了,但找不到正确的方法。对不起英语。谢谢。

【问题讨论】:

    标签: python ubuntu terminal subprocess


    【解决方案1】:

    您可以使用 os 模块来做到这一点:

    #!/usr/bin/env python
    
    import os
    output = os.listdir('path_to_folder')  # output is a list
    # Do whatever you want to output
    

    您可以在https://docs.python.org/3/library/os.html 阅读更多关于 os 模块还可以做什么的信息。请注意,模块中的方法可以跨不同的操作系统移植,因此您实际上可以在 Ubuntu 之外使用您的脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多