相关疑难解决方法(0)

从subprocess.Popen异步读取stdout

我正在使用subprocess.popen运行子程序.当我从命令窗口(cmd.exe)启动我的Python程序时,程序会随着程序的发展在窗口中写入一些信息和日期.

当我不在命令窗口中运行我的Python代码时,它会为这个子程序的输出打开一个新的命令窗口,我想避免这种情况.当我使用以下代码时,它不会显示cmd窗口,但它也不会打印状态:

p = subprocess.Popen("c:/flow/flow.exe", shell=True, stdout=subprocess.PIPE)
print p.stdout.read()
Run Code Online (Sandbox Code Playgroud)

如何在程序输出中显示子程序的输出?

python windows subprocess

6
推荐指数
1
解决办法
1万
查看次数

Python命令行输入?

可能重复:
你如何读取python中的stdin

什么是从命令行获取信息的最佳/最简单的方法.

例如,我将运行一堆shell脚本,它们返回:

200 SOLUTIONS_REVISION 
or 
400 SOLUTIONS_REVISION
Run Code Online (Sandbox Code Playgroud)

在我运行每个脚本之后.我需要在python中捕获这些"返回"的字符串作为字符串(以检查它是否通过(200)或失败(400).最好的方法是什么(我是一个完整的新的python和我的搜索似乎主要是返回命令行争论.

谢谢(最好也是python 2.x)

python

5
推荐指数
1
解决办法
2849
查看次数

如何使用子进程和Popen从长时间运行的进程返回stdout?

我正在使用subprocess.Popen()的一个非常基本的设置,并将stdout指向一个变量,我稍后将其返回到我的python脚本的不同部分.

这是我的基本Popen代码:

process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode
print out
Run Code Online (Sandbox Code Playgroud)

这适用于许多类似ls -al或类似的基本用例.但是,我想知道如何处理从更长(或无限期)运行过程中定期和一致地获取输出,例如tail -f foo.log.有没有办法在循环中定期读取stdout?或者产生一个线程来检查并定期返回每个线程?这里最好的方法是什么?

谢谢!

python shell subprocess stdout

5
推荐指数
1
解决办法
2628
查看次数

进程终止后,Popen对象的返回码为None

我正在运行一个使用过程Popen.我需要等待进程终止.我正在检查这个过程已经通过了returncode.当returncode不同None的过程必须已经终止.问题是,当print_outputFalsereturncode总是None,即使处理完成运行(终止).但是,这是不是这样的时候print_outputTrue.我正在使用以下代码来运行该过程:

def run(command, print_output=True):
    # code mostly from: http://sharats.me/the-ever-useful-and-neat-subprocess-module.html
    from subprocess import Popen, PIPE
    from threading import Thread
    from queue import Queue, Empty
    from time import sleep

    io_q = Queue()

    def stream_watcher(identifier, stream):
        for line in stream:
            io_q.put((identifier, line))

        if not stream.closed:
            stream.close()

    with Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True) as proc:
        if print_output:

            Thread(target=stream_watcher, name='stdout-watcher', args=('STDOUT', proc.stdout)).start()
            Thread(target=stream_watcher, name='stderr-watcher', args=('STDERR', proc.stderr)).start() …
Run Code Online (Sandbox Code Playgroud)

python subprocess

5
推荐指数
2
解决办法
5564
查看次数

Python逐行从子进程捕获stdout

我已经阅读了很多与此相关的问题并且学到了很多,但我仍然无法解决我的问题.我正在构建一个运行c ++可执行文件的wxPython应用程序,并实时显示该可执行文件中的stdout.我试图让这项工作遇到几个奇怪的结果.这是我目前的设置/问题:

//test.cc (compiled as test.out with gcc 4.5.2)
#include <stdio.h>
int main()
{
  FILE* fh = fopen("output.txt", "w");
  for (int i = 0; i < 10000; i++)
  {
      printf("Outputting: %d\n", i);
      fprintf(fh, "Outputting: %d\n", i);
  }
  fclose(fh);
  return 0;
}

#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
  self.externalBinary = subprocess.Popen(['./test.out'], shell=False, stdout=subprocess.PIPE)
  while not self.wantAbort:
      line = self.externalBinary.stdout.readline()
      wx.PostEvent(self.notifyWindow, Result_Event(line, Result_Event.EVT_STDOUT_ID))
    print('Subprocess still running')
  print('Subprocess aborted smoothly')
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的代码,子进程需要很长时间才能完成,即使它只需要写出数据并退出.但是,如果我运行以下内容,它会很快完成:

#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
  outFile = open('output.txt', 'r+') …
Run Code Online (Sandbox Code Playgroud)

c c++ python multithreading wxpython

3
推荐指数
1
解决办法
3100
查看次数

用 python 封装 bash 脚本

我刚刚找到了这个很棒的 wget 包装器,我想使用 subprocess 模块将其重写为 python 脚本。然而,事实证明这很棘手,给了我各种各样的错误。

download()
{
    local url=$1
    echo -n "    "
    wget --progress=dot $url 2>&1 | grep --line-buffered "%" | \
    sed -u -e "s,\.,,g" | awk '{printf("\b\b\b\b%4s", $2)}'

    echo -ne "\b\b\b\b"
    echo " DONE"
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样调用:

file="patch-2.6.37.gz"
echo -n "Downloading $file:"
download "http://www.kernel.org/pub/linux/kernel/v2.6/$file"
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

来源: http: //fitnr.com/showing-file-download-progress-using-wget.html

python bash shell subprocess wrapper

0
推荐指数
1
解决办法
7213
查看次数

Python和shell中的多线程

我有一个名为"nn.sh"的shell脚本,它在本地网络中获取一个ip地址并通过SSH连接到该ip,然后从该ip连续读取一些数据,并将结果附加到名为"log.txt"的文件中.服务器.

我需要编写一个Python代码在服务器上运行,该代码可能使用多线程在一个线程中运行此脚本,然后在另一个线程中读取文件"log.txt"中已有的值.我该怎么做呢?

我写了以下代码:

#!/usr/bin/python
import threading
import time
from subprocess import call, Popen, PIPE

exitFlag = 0

class loggerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        print "Logging thread started ..."
    def run(self):
        with open("log.txt","at") as log: 
                call(['/bin/sh', 'nn.sh', '172.20.125.44', '10'], stdout = log)

class readerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        print "Reading thread started ..."
    def run(self):
        while 1:
                with open("log.txt","r") as log:
                        lines = log.read().split("\n")
                        print "Reader thread  ..."
                        print lines[-1]


thread1 = loggerThread()
thread2 = readerThread()

thread1.start()
thread2.start()
Run Code Online (Sandbox Code Playgroud)

这里也是"nn.sh"的内容:

ssh -o IdentityFile=~/Dropbox/ALI/id_rsa -l …
Run Code Online (Sandbox Code Playgroud)

python multithreading

0
推荐指数
1
解决办法
1681
查看次数

阻止sys.stdout写入文本文件

我正在使用python sys将我的stdout保存到文本文件中.

sys.stdout=open('OLSYield.txt','w')
Run Code Online (Sandbox Code Playgroud)

但是我只想要一部分stdout转到文本.如何停止写入txt文件并重定向回终端或控制台?

所以看起来应该是这样的

sys.stdout=open('OLSYield.txt','w')
print "helloWorld appears in text file"

sys.stdout=close('OLSYield.txt','w')
print "helloWorld appears in console"
Run Code Online (Sandbox Code Playgroud)

我不确定我应该用什么命令关闭 stdout=open

python sys spyder

0
推荐指数
1
解决办法
4076
查看次数

标签 统计

python ×8

subprocess ×4

multithreading ×2

shell ×2

bash ×1

c ×1

c++ ×1

spyder ×1

stdout ×1

sys ×1

windows ×1

wrapper ×1

wxpython ×1