Ipython Jupyter Notebook中有一个有趣的选项可以直接从笔记本中执行命令行语句.例如:
! mkdir ...
! python file.py
Run Code Online (Sandbox Code Playgroud)
此外 - 此代码可以使用os以下命令运行:
import os
os.system('cmd command')
Run Code Online (Sandbox Code Playgroud)
但是如何运行交互式shell命令.例如:
!conda install package
Run Code Online (Sandbox Code Playgroud)
可能需要将来的input([Y]/N)或文件夹位置,但不接受进一步的输入.
我在使用子进程模块重定向另一个程序的stdio时遇到问题.只是从stdout读取导致挂起,并且Popen.communicate()可以工作,但它在读/写后关闭管道.实现这个最简单的方法是什么?
我在Windows上玩这个:
import subprocess
proc = subprocess.Popen('python -c "while True: print \'Hi %s!\' % raw_input()"',
shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
proc.stdin.write('world\n')
proc_read = proc.stdout.readline()
if proc_read:
print proc_readRun Code Online (Sandbox Code Playgroud) 我正在尝试使用subprocessPython中的模块与读取标准输入并以流式方式写入标准输出的进程进行通信.我希望从生成输入的迭代器获取子进程读取行,然后从子进程读取输出行.输入和输出线之间可能没有一对一的对应关系.如何从返回字符串的任意迭代器中提供子进程?
下面是一些示例代码,它给出了一个简单的测试用例,以及我尝试过的某些方法因某些原因而无法正常工作:
#!/usr/bin/python
from subprocess import *
# A really big iterator
input_iterator = ("hello %s\n" % x for x in xrange(100000000))
# I thought that stdin could be any iterable, but it actually wants a
# filehandle, so this fails with an error.
subproc = Popen("cat", stdin=input_iterator, stdout=PIPE)
# This works, but it first sends *all* the input at once, then returns
# *all* the output as a string, rather than giving me an iterator over
# …Run Code Online (Sandbox Code Playgroud) 一直试图从运行了一点的 Powershell 脚本读取标准输出,根据它正在 ping 的计算机数量生成输出。
试图让数据流入文本框,但毕竟我已经尝试过了,我似乎只能让它一次提供所有输出。
一直试图不使用subprocess.communicate(),因为它似乎也一次提供所有输出。
这是代码:
from tkinter import *
import os
from subprocess import Popen, PIPE
window = Tk()
window.title( 'PowerShell Script Temp' )
frame = Frame(window)
fldrPath = r"C:/Users/firstname.lastname/Downloads/Powershell Development/Monthly Scans/"
listbox = Listbox(frame)
listbox.configure(width=50)
for name in os.listdir(fldrPath):
listbox.insert('end', name)
def selection():
fileList = listbox.curselection()
for file in fileList:
os.chdir(fldrPath)
# Right here is the problematic section
with Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], stdout=PIPE, bufsize=1,
universal_newlines=True) as p:
for line in …Run Code Online (Sandbox Code Playgroud) python ×3
subprocess ×2
cmd ×1
io ×1
ipython ×1
jupyter ×1
powershell ×1
python-3.x ×1
tkinter ×1