在本文中,我们将详细介绍如何以一般方式使由Python函数运行的可执行文件的终端输出静音?的各个方面,并为您提供关于python语言采用的相关解答,同时,我们也将为您带来关于c–修改自身的正在运行的可
在本文中,我们将详细介绍如何以一般方式使由Python函数运行的可执行文件的终端输出静音?的各个方面,并为您提供关于python语言采用的相关解答,同时,我们也将为您带来关于c – 修改自身的正在运行的可执行文件、c++可执行文件 管道 python 管道 c++可执行文件、delphi – 如何获取正在运行的可执行文件的版本?、Ipython笔记本输出静音的有用知识。
本文目录一览:- 如何以一般方式使由Python函数运行的可执行文件的终端输出静音?(python语言采用)
- c – 修改自身的正在运行的可执行文件
- c++可执行文件 管道 python 管道 c++可执行文件
- delphi – 如何获取正在运行的可执行文件的版本?
- Ipython笔记本输出静音
如何以一般方式使由Python函数运行的可执行文件的终端输出静音?(python语言采用)
我想禁止运行可执行程序的函数产生的所有终端输出。
我试图通过使用上下文管理器来抑制Python函数的输出,该上下文管理器在每次调用函数时临时重新定义stdout和stderr。这样可以抑制print
函数调用产生的终端输出,但是当函数调用产生终端输出的可执行文件时,它似乎不起作用。
那么,如何抑制Python函数调用的可执行文件的输出呢?
我的代码如下。我提供了一个示例函数,该函数调用ls
以尝试说明我要抑制的终端输出的种类(尽管我要处理的函数是不同的)。
#!/usr/bin/env pythonimport osimport subprocessimport sysdef main(): print("hello") with silence(): print("there") print("world") with silence(): engage_command(command = "ls")class silence(object): def __init__( self, stdout = None, stderr = None ): if stdout == None and stderr == None: devnull = open(os.devnull, "w") stdout = devnull stderr = devnull self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__( self ): self.old_stdout = sys.stdout self.old_stderr = sys.stderr self.old_stdout.flush() self.old_stderr.flush() sys.stdout = self._stdout sys.stderr = self._stderr def __exit__( self, exc_type, exc_value, traceback ): self._stdout.flush() self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderrdef engage_command( command = None ): process = subprocess.Popen( [command], shell = True, executable = "/bin/bash") process.wait() output, errors = process.communicate() return outputif __name__ == "__main__": main()
在我的特殊情况下,我正在尝试运行以下功能(而不是ls
上面的功能):
with propyte.silence(): stream = pyaudio.PyAudio().open( format = pyaudio.PyAudio().get_format_from_width(1), channels = 1, rate = bitrate, output = True )
运行时,将产生如下输出:
ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slaveALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slaveALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rearALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfeALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.sideALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slaveCannot connect to server socket err = No such file or directoryCannot connect to server request channeljack server is not running or cannot be startedJackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlockJackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
我想抑制该输出。
编辑:测试由@Matthias提供的解决方案
#!/usr/bin/env pythonimport contextlibimport osimport subprocessimport sysdef main(): print("hello") with silence(): print("there") print("world") with silence(): engage_command(command = "ls")@contextlib.contextmanagerdef silence(): devnull = os.open(os.devnull, os.O_WRONLY) old_stderr = os.dup(2) sys.stderr.flush() os.dup2(devnull, 2) os.close(devnull) try: yield finally: os.dup2(old_stderr, 2) os.close(old_stderr)def engage_command( command = None ): process = subprocess.Popen( [command], shell = True, executable = "/bin/bash") process.wait() output, errors = process.communicate() return outputif __name__ == "__main__": main()
我没有成功抑制来自print
或的终端输出ls
,我不确定为什么。
答案1
小编典典您可以从PyAudio切换到sounddevice模块,该模块已经负责使终端输出静音(请参阅#12)。这是在此完成的操作(使用CFFI):
from cffi import FFIimport osffi = FFI()ffi.cdef("""/* from stdio.h */FILE* fopen(const char* path, const char* mode);int fclose(FILE* fp);FILE* stderr; /* GNU C library */FILE* __stderrp; /* Mac OS X */""")try: stdio = ffi.dlopen(None) devnull = stdio.fopen(os.devnull.encode(), b''w'')except OSError: returntry: stdio.stderr = devnullexcept KeyError: try: stdio.__stderrp = devnull except KeyError: stdio.fclose(devnull)
如果您想要一个纯Python解决方案,可以尝试以下上下文管理器:
import contextlibimport osimport sys@contextlib.contextmanagerdef ignore_stderr(): devnull = os.open(os.devnull, os.O_WRONLY) old_stderr = os.dup(2) sys.stderr.flush() os.dup2(devnull, 2) os.close(devnull) try: yield finally: os.dup2(old_stderr, 2) os.close(old_stderr)
这是关于该主题的非常有用的博客文章:http : //eli.thegreenplace.net/2015/redirecting-all-
kinds-of-stdout-in-python/。
更新:
上面的上下文管理器使标准错误输出(stderr
)静音,该错误用于原始问题中提到的来自PortAudio的烦人消息。如要删除标准输出(stdout
),就像在更新的问题中一样,您必须将替换sys.stderr
为sys.stdout
,并将文件描述符2
替换为数字1
:
@contextlib.contextmanagerdef ignore_stdout(): devnull = os.open(os.devnull, os.O_WRONLY) old_stdout = os.dup(1) sys.stdout.flush() os.dup2(devnull, 1) os.close(devnull) try: yield finally: os.dup2(old_stdout, 1) os.close(old_stdout)
c – 修改自身的正在运行的可执行文件
具体来说,我希望能够读取/写入exe文件本身存储的一些数据.我不需要(或希望)修改可执行代码.
在常规窗口中,我可以使用字符串资源和UpdateResource函数,但在WinCE中不存在.
遗憾的是,CreateFile因文件已被使用而失败.
有人有任何其他建议吗?
解决方法
我对Windows-CE并不是特别熟悉,但是如果需要,你可以复制文件,编辑副本,删除第一个,然后运行另一个.这是一种效率低下的方法,但是如果你只需要在程序范围内执行一次或两次并且速度不是问题,我想你可以这样做:
#include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc,char * argv[]) { // Check if this IS the copy: if (argv[0].find(argv[1]) != string::npos) { system("taskkill -IM myOLDfile.exe"); // Stop the old one running,system("del myOLDfile.exe"); // Then delete it. } ifstream myself(argv[0]); // argv[0] is the program itself string fullcode; string line; if (file.is_open()) { while (file.good()) { getline(myself,line); line.append("\n"); fullcode.append(line); } } myself.close(); // Do whatever you need to do to the code here. ofstream newcode("myNEWfile.exe"); newcode.write(fullcode); newcode.close(); system("myNEWfile.exe myNEWfile.exe"); // Starts new file. Also,not a typo. }
祝你的项目好运!
c++可执行文件 管道 python 管道 c++可执行文件
在centos中使用管道进行参数的传输
运行格式 ./c++A | python3 p.py | ./c++B
python脚本中使用标准输入和输出 stdin 和 stdout,python脚本参数是传输不到./c++B可执行文件的。
python 脚本中要使用
while True:
line=input()
............
print(line)
不要写
for line in sys.stdin:
print(line)
本人没有学过python,具体什么原因也不清楚,有请python大佬们给个解释吧
delphi – 如何获取正在运行的可执行文件的版本?
我一直在使用GetFileVersionInfo(ParamStr(0),...)
:
filename := PChar(ExtractShortPathName(ParamStr(0))); //Get the number of bytes he have to allocate for the file information structure dwInfoLength := GetFiLeversionInfoSize(lptstrFilename,{var}dwHandle); //Get version info GetMem(pInfoData,dwInfoLength); GetFiLeversionInfo(lptstrFilename,dwHandle,dwInfoLength,pInfoData); //Set what information we want to extract from pInfoData lpSubBlock := PChar(Chr(92)+Chr(0)); //Extract the desired data from pInfoData into the Fileinformation structure VerQueryValue(pInfoData,lpSubBlock,PFileinformation,LengthOfReturned);
这种技术的问题是它需要Windows加载器到load the image before the resources can be read.我使用IMAGE_FILE_NET_RUN_FROM_SWAP
图像标志(in order to avoid in-page exceptions on a fiddly network)构建我的应用程序.
这会导致Windows加载程序再次通过网络加载整个图像,而不是仅仅查看“我”.由于我在启动时检查并保存了我自己的版本,因此6秒的应用程序启动变成了10秒的应用程序启动.
我如何阅读我的版本,我正在运行的应用程序?
我会假设Windows没有API来读取正在运行的进程的版本,只有我加载的文件(如果文件不再存在,那么它无法读取任何版本信息).
但我也假设有可能从我的进程自己的内存中读取版本资源(当然不是Administrators或Debuggers组的成员).
我可以阅读我的流程版本吗?
相关奖金问题:如何从我而不是通过网络加载PE图像资源?
解决方法
How to determine Delphi Application Version
我已经知道如何确定一个应用程序版本,但@StijnSanders提出了“更好”的方式,正是因为我正在打击的原因:
I most strongly recommend not to use GetFiLeversion when you want to kNow the version of the executable that is currently running! I have two pretty good reasons to do this:
- The executable may be unaccessible (disconnected drive/share),or changed (.exe renamed to .bak and replaced by a new .exe without the running process being stopped).
- The version data you’re trying to read has actually already been loaded into memory,and is available to you by loading this resource,which is always better than to perform extra (relatively slow) disk operations.
我改编成:
function GetModuLeversion(Instance: THandle; out iMajor,iMinor,iRelease,iBuild: Integer): Boolean; var fileinformation: PVSFIXEDFILEINFO; verlen: Cardinal; rs: TResourceStream; m: TMemoryStream; resource: HRSRC; begin //You said zero,but you mean "us" if Instance = 0 then Instance := HInstance; //UPDATE: Workaround bug in Delphi if resource doesn't exist resource := FindResource(Instance,1,RT_VERSION); if (resource = 0) begin iMajor := 0; iMinor := 0; iRelease := 0; iBuild := 0; Result := False; Exit; end; m := TMemoryStream.Create; try rs := TResourceStream.CreateFromID(Instance,RT_VERSION); try m.copyFrom(rs,rs.Size); finally rs.Free; end; m.Position:=0; if not VerQueryValue(m.Memory,'\',/*var*/Pointer(fileinformation),/*var*/verlen) then begin iMajor := 0; iMinor := 0; iRelease := 0; iBuild := 0; Exit; end; iMajor := fileinformation.dwFiLeversionMS shr 16; iMinor := fileinformation.dwFiLeversionMS and $FFFF; iRelease := fileinformation.dwFiLeversionLS shr 16; iBuild := fileinformation.dwFiLeversionLS and $FFFF; finally m.Free; end; Result := True; end;
警告:由于Delphi中的错误,上面的代码有时会崩溃:
rs := TResourceStream.CreateFromID(Instance,RT_VERSION);
如果没有版本信息,Delphi会尝试引发异常:
procedure TResourceStream.Initialize(Instance: THandle; Name,ResType: PChar); procedure Error; begin raise EResNotFound.CreateFmt(SResNotFound,[Name]); end; begin HResInfo := FindResource(Instance,Name,ResType); if HResInfo = 0 then Error; ... end;
当然,错误是PChar并不总是指向ansi char的指针.对于非命名资源,它们是整数常量,强制转换为PChar.在这种情况下:
Name: PChar = PChar(1);
当Delphi尝试构建异常字符串,并取消引用指针0x00000001时,它会触发并访问违规.
修复是首先手动调用FindResource(Instance,RT_VERSION):
var ... resource: HRSRC; begin ... resource := FindResource(Instance,RT_VERSION); if (resource = 0) begin iMajor := 0; iMinor := 0; iRelease := 0; iBuild := 0; Result := False; Exit; end; m := TMemoryStream.Create; ...
Note: Any code is released into the public domain. No attribution required.
Ipython笔记本输出静音
for i in tqdm(range(len(frd_acct_id_unique))): ... output cell: |#---------| 694/6146 11% [elapsed: 01:16 left: 10:04,9.02 iters/sec]**OUTPUT MUTED**
解决方法
关于如何以一般方式使由Python函数运行的可执行文件的终端输出静音?和python语言采用的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于c – 修改自身的正在运行的可执行文件、c++可执行文件 管道 python 管道 c++可执行文件、delphi – 如何获取正在运行的可执行文件的版本?、Ipython笔记本输出静音的相关知识,请在本站寻找。
本文标签: