GVKun编程网logo

如何将Tab键发送到python子进程的stdin(tab键在python中的作用)

11

在这篇文章中,我们将带领您了解如何将Tab键发送到python子进程的stdin的全貌,包括tab键在python中的作用的相关情况。同时,我们还将为您介绍有关Python-如何终止使用shell=T

在这篇文章中,我们将带领您了解如何将Tab键发送到python子进程的stdin的全貌,包括tab键在python中的作用的相关情况。同时,我们还将为您介绍有关Python-如何终止使用shell=True启动的python子进程、Python子脚本占用了所有的stdin、Python子进程Grep、python子进程proc.stderr.read()引入额外的行?的知识,以帮助您更好地理解这个主题。

本文目录一览:

如何将Tab键发送到python子进程的stdin(tab键在python中的作用)

如何将Tab键发送到python子进程的stdin(tab键在python中的作用)

背景:
我有一个Python子进程,该子进程连接到类似shell的应用程序,该应用程序使用readline库处理输入,并且该应用程序具有TAB完整的例程来执行命令输入,就像bash一样。生成子进程,如下所示:

def get_cli_subprocess_handle():    return subprocess.Popen(                            ''/bin/myshell'',                            shell=False,                            stdin=subprocess.PIPE,                            stdout=subprocess.PIPE,                            stderr=subprocess.STDOUT,                            )

一切正常,除了制表符完整。每当我的Python程序将tab字符传递''\t''给子进程时,我在STDIN中获得5个空格,而不是触发readline库的tab-
complete例程。:(

问题: 我可以发送什么到子进程的STDIN来触发孩子的制表符完成功能?也许以另一种方式问:如果可能的话,我该如何发送TAB 密钥而不是TAB 字符

答案1

小编典典

类似shell的应用程序可能会区分连接到stdin的终端和连接到stdin的管道。许多Unix实用程序只是为了优化其缓冲(行与块)而这样做,而类似于shell的实用程序可能会禁用批输入(即PIPE)上的命令完成功能,以避免意外结果。命令完成实际上是一项交互式功能,需要终端输入。

检出pty模块,并尝试使用主/从对作为子流程的管道。

Python-如何终止使用shell=True启动的python子进程

Python-如何终止使用shell=True启动的python子进程

我正在使用以下命令启动子流程:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

但是,当我尝试杀死使用:

p.terminate()

要么

p.kill()

该命令一直在后台运行,所以我想知道如何才能真正终止该过程。

请注意,当我使用以下命令运行命令时:

p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

发出时,它确实成功终止p.terminate()

答案1

小编典典

使用进程组,以便能够向组中的所有进程发送信号。为此,你应该将会话ID附加到派生/子进程的父进程中,在你的情况下,这是一个外壳程序。这将使其成为流程的小组负责人。因此,现在,当信号发送到流程组负责人时,它便被传输到该组的所有子流程。

这是代码:

import osimport signalimport subprocess# The os.setsid() is passed in the argument preexec_fn so# it''s run after the fork() and before  exec() to run the shell.pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,                        shell=True, preexec_fn=os.setsid) os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

Python子脚本占用了所有的stdin

Python子脚本占用了所有的stdin

在bash脚本中运行python脚本时,我发现了raw_input / readline的一些奇怪行为。

简而言之,当所有的标准input一次(每个条目由一个新的行分隔)到一个父脚本时,bash子脚本将只采取他们需要的标准input,而python子脚本将消耗所有的标准input,为下一个孩子。 我想出了一个简单的例子来说明我的意思:

父脚本(parent.sh)

#!/bin/bash ./child.sh ./child.sh ./child.py ./child.py

Bash子脚本(child.sh)

#!/bin/bash read -a INPUT echo "sh: got input: ${INPUT}"

Python子脚本(child.py)

#!/usr/bin/python -B import sys INPUT = raw_input() print "py: got input: {}".format(INPUT)

预期结果

./parent.sh <<< $''aanbbnccndd'' >> sh: got input: aa >> sh: got input: bb >> py: got input: cc >> py: got input: dd

实际结果

./parent.sh <<< $''aanbbnccnddn'' >> sh: got input: aa >> sh: got input: bb >> py: got input: cc >> Traceback (most recent call last): >> File "./child.py",line 5,in <module> >> INPUT = raw_input() >> EOFError: EOF when reading a line

raw_input似乎清除标准input中的所有其余行。 使用sys.stdin.readline而不是raw_input不会引发EOFError,但是收到的input是一个空string,而不是预期的“dd”。

这里发生了什么? 我怎样才能避免这种行为,使最后一个子脚本收到预期的input?

问题与Python平扫脚本

Bash或Powershell脚本帮助需要帮助

两种情况下哪个更快?

bash及其引用规则的问题

从捕获输出的函数中退出一个bash脚本

编辑 :可以肯定的是,我添加了几行到标准input,结果是一样的:

./parent.sh <<< $''aanbbnccnddnffneen'' >> sh: got input: aa >> sh: got input: bb >> py: got input: cc >> Traceback (most recent call last): >> File "./child.py",in <module> >> INPUT = raw_input() >> EOFError: EOF when reading a line

从批处理Linux到Windows的awk和sed命令。 如何转换?

这个基本的shell脚本导出的东西有什么问题

如何在每个Bash命令的开头添加一些内容?

“ – ”运算符在Linux中究竟做了什么?

Linux读取空格和特殊字符

这是展示相同问题的一种更简单的方法:

printf "%sn" foo bar | { head -n 1 head -n 1 }

根据所有帐户,这看起来应该打印两行,但bar是神秘的失踪。

这是因为阅读线是谎言。 UNIX编程模型不支持它。

相反,基本上所有的工具都是使用整个缓冲区,划出第一行,并留下下一个缓冲区的其余部分。 对于head ,Python raw_input() ,C fgets() ,Java BufferedReader.readLine()以及几乎所有其他东西都是如此。

由于UNIX统计整个缓冲区为消耗状态,无论程序实际使用的是多少,缓冲区的其余部分在程序退出时被丢弃。

然而, bash工作原理是:逐字节读取,直到达到换行。 这是非常低效的,但是它允许read只从流中消耗一行,剩下的部分留在下一个进程中。

你可以通过打开一个原始的,无缓冲的阅读器来做同样的事情:

import sys import os f = os.fdopen(sys.stdin.fileno(),''rb'',0) line=f.readline()[:-1] print "Python read: ",line

我们可以用同样的方法来测试:

printf "%sn" foo bar | { python myscript python myscript }

版画

Python read: foo Python read: bar

python解释器会默认缓冲标准输入。 您可以使用-u选项来禁用此行为,虽然效率较低。

parent.sh

/bin/bash ./child.sh ./child.sh python -u child.py python -u child.py

产量

./parent.sh <<< $''aanbbnccndd'' sh: got input: aa sh: got input: bb py: got input: cc py: got input: dd

总结

以上是小编为你收集整理的Python子脚本占用了所有的stdin全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Python子进程Grep

Python子进程Grep

我正在尝试使用subprocess模块​​在python脚本中使用grep命令。

这是我所拥有的:

userid = ''foo12''p = subprocess.Popen([''grep'', "%s *.log"%userid], stdout=subprocess.PIPE)

它什么也不返回。我不完全确定自己在做什么错,所以有人可以解释一下。我正在使用的当前方法有效,方法是添加shell =
true,使其输出正确的输出,但是正如帮助页面所指出的那样,这是不安全的。我需要帮助以使此工作正常进行,以便我的脚本不是不安全的。

答案1

小编典典

我认为您遇到了两个问题:

  1. 这个电话:
    p = subprocess.Popen([''grep'', "%s *.log"%userid]...

除非shell=True将参数列表直接传递给os.execvp,否则它将无法按预期工作,这要求每个项目都是代表参数的单个字符串。您已经将
两个单独的参数 压缩到一个字符串中(换句话说,grep将“ foo12 *.log”解释为要搜索的 模式 ,而不是模式+文件列表)。

您可以通过以下方式解决此问题:

    p = subprocess.Popen([''grep'', userid, ''*.log'']...)
  1. 第二个问题是,再次没有shell=Trueexecvp*.log将不知道您的意思并将其直接传递给grep,而无需通过外壳的通配符扩展机制。如果您不想使用shell=True,则可以执行以下操作:
    import glob

    args = [‘grep’, userid]
    args.extend(glob.glob(‘*.log’)
    p = subprocess.Popen(args, …)

python子进程proc.stderr.read()引入额外的行?

python子进程proc.stderr.read()引入额外的行?

我想运行一些命令并抓取输出到stderr的任何内容.我有两个版本的功能来做到这一点
版本1.

def Getstatusoutput(cmd):
    """Return (status,output) of executing cmd in a shell."""

    import sys
    mswindows = (sys.platform == "win32")

    import os
    if not mswindows:
        cmd = '{ ' + cmd + '; }'

    pipe = os.popen(cmd + ' 2>&1','r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts,text  


版本2

def Getstatusoutput2(cmd):
    proc = subprocess.Popen(cmd,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
    return_code = proc.wait()
    return return_code,proc.stdout.read(),proc.stderr.read()

第一个版本按照我的预期打印stderr输出.第二个版本在每行后打印一个空行.我怀疑这是由于版本1中的文本[-1:]行…但我似乎无法在第二版中做类似的事情.任何人都可以解释我需要做什么才能使第二个函数生成与第一个函数相同的输出而在它们之间没有额外的行(并且在最后)?

更新:这是我打印输出的方式
这就是我打印的方式

      status,output,error = Getstatusoutput2(cmd)
      s,oldOutput = Getstatusoutput(cmd)
      print "oldOutput = <<%s>>" % (oldOutput)
      print "error = <<%s>>" % (error)
最佳答案
您可以添加.strip():

def Getstatusoutput2(cmd):
    proc = subprocess.Popen(cmd,proc.stdout.read().strip(),proc.stderr.read().strip()

Python string Docs:

string.strip(s[,chars])

Return a copy of the string with leading and
trailing characters removed. If chars is omitted or None,whitespace
characters are removed. If given and not None,chars must be a string;
the characters in the string will be stripped from the both ends of
the string this method is called on.

string.whitespace

A string containing all characters that are
considered whitespace. On most systems this includes the characters
space,tab,lineFeed,return,formFeed,and vertical tab.

关于如何将Tab键发送到python子进程的stdintab键在python中的作用的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Python-如何终止使用shell=True启动的python子进程、Python子脚本占用了所有的stdin、Python子进程Grep、python子进程proc.stderr.read()引入额外的行?等相关知识的信息别忘了在本站进行查找喔。

本文标签: