首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python命令行上输入python命令

在python命令行上输入python命令
EN

Stack Overflow用户
提问于 2014-03-15 10:46:13
回答 3查看 330关注 0票数 6

标题可能令人困惑,但基本上我希望能够做到以下几点:

代码语言:javascript
复制
import subprocess

subprocess.call(["python"])
subprocess.call(["import", "antigravity"])
subprocess.check_call(["print","\"This is so meta\" "])
subprocess.call(["exit()"])

预期的行为将是打开python终端会话,然后打开xkcd漫画353,在命令行中打印“this is so meta”,最后退出python命令行。

基本上,我希望能够打开python会话,并从我的python脚本中运行命令。我还希望能够检查我在脚本中运行的命令的输出。这个是可能的吗?如果是的话,我需要使用哪个库呢?子进程会这样做吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-15 11:34:58

就像这样..。

代码语言:javascript
复制
import subprocess
proc = subprocess.Popen(
    'python',stdout=subprocess.PIPE,
    stdin=subprocess.PIPE)
proc.stdin.write('import antigravity\n')
proc.stdin.write('print "something"\n')
proc.stdin.close()
result = proc.stdout.read()
print result

因此,我们正在创建一个流程,并告诉它输入将来自stdin (就像有人输入)。然后编写任何我们喜欢的内容,然后从stdout读取响应(通常会打印到屏幕上)。

票数 3
EN

Stack Overflow用户

发布于 2014-03-15 11:42:11

您也可以使用代码模块

代码语言:javascript
复制
import code
console = code.InteractiveConsole()
console.push('import antigravity')
console.push('print "something"')

如果出于某种原因,您希望在子进程中运行此程序,则可以使用多处理模块

代码语言:javascript
复制
import code
import multiprocessing as mp

def work():
    console = code.InteractiveConsole()
    console.push('import antigravity')
    console.push('print "something"')

if __name__ == '__main__':    
    proc = mp.Process(target=work)
    proc.start()
    proc.join()

要将stdout重定向到变量:

代码语言:javascript
复制
import code
import sys

class MyStream(object):
    def __init__(self, target):
        self.target = target
        self.value = None
    def write(self, s):
        if s.strip():
            self.value = s

sys.stdout = stream = MyStream(sys.stdout)
console = code.InteractiveConsole(locals=locals())
console.push('import antigravity')
console.push('print "something"')
sys.__stdout__.write('output: {}\n'.format(stream.value))

版画

代码语言:javascript
复制
output: something

请注意,consolesys.stdout已被重定向到MyStream(sys.stdout)。它不打印任何东西,而是将最后一个字符串存储在self.value中。要打印到该字符串,可以使用sys.__stdout__.write (注意下划线)。

票数 2
EN

Stack Overflow用户

发布于 2014-03-15 11:42:40

如果您需要与进程通信,则应该使用communicate()方法而不是stdin.write()方法,否则您会发现一些不理想的效果。

警告使用child ()而不是.stdin.write、.stdout.read或.stderr.read来避免由于其他OS管道缓冲区填充和阻塞子进程而导致的死锁。

来源:http://docs.python.org/2/library/subprocess.html#popen-objects

代码语言:javascript
复制
from subprocess import PIPE, STDOUT, Popen

e = Popen(["/usr/local/bin/python3"], stdout = PIPE, stdin = PIPE, stderr = STDOUT, shell = False)

out, err = e.communicate(b"""
import sys
print('Interactive python version: %s' % str(sys.version))
sys.exit(4)
""")
e.wait()
print ('Exit code', e.returncode)
print ('Output', out)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22422727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档