我一直在尝试使用这段代码重定向自定义django命令的标准输出:
from django.core.management.base import BaseCommand
from django.core import management
class Command(BaseCommand):
def handle(self, *args, **options):
f = open('/tmp/output', 'r+')
management.call_command('basequery', 'list', 'log', stdout=f)
f.close()
Run Code Online (Sandbox Code Playgroud)
但是,当我从manage.py调用它时,控制台上会出现标准输出,并且/ tmp/output文件已创建但为空.
这是我正在尝试做的django 文档
我正在尝试制作一个脚本,将桌面上的所有.txt文件移动到desktop/org,代码如下:
import os
import shutil
userhome = os.path.expanduser('~')
src = userhome + '/Desktop/'
dst = src+ 'org/'
def main():
txtlist = os.listdir(src)
for file in txtlist:
sortFiles(file)
def sortFiles(file):
if file.endswith(".txt"):
shutil.move(src+file,dst)
main()
Run Code Online (Sandbox Code Playgroud)
如果我执行.py,我会收到此错误:AttributeError:'module'对象没有属性'copy'.但是,如果我擦除最后一行"main()"并将此脚本作为模块导入python命令行,我从那里调用.main()它可以很好地工作.如何将此作为脚本工作?
Traceback (most recent call last):
File "C:\Python32\org.py", line 3, in <module>
import shutil
File "C:\Python32\lib\shutil.py", line 14, in <module>
import tarfile
File "C:\Python32\lib\tarfile.py", line 50, in <module>
import copy
File "C:\Python32\lib\copy.py", line 61, in <module>
from org.python.core import PyStringMap
File "C:\Python32\org.py", line …Run Code Online (Sandbox Code Playgroud) 因此,我使用的是第三方库中的 method_x,每次使用时都会打印警告。由于我正在编写一些旨在从 cli 获取用户输入的内容,因此我想阻止这种烦人的打印。
import module_x
module_x.method_x() # Has expected behaviour but prints an annoying warning
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来阻止函数内的所有打印语句?也许用一些东西包装方法或暂时禁用标准输出?
编辑:我最终使用了日志模块的一种方法来捕获警告并将它们重定向到日志文件。这是我制作的装饰器:
logging.basicConfig(filename='log/log', level=logging.WARNING)
class redirect_warnings_to_log(object):
def __init__(self, f):
self.f = f
def __call__(self, args):
logging.captureWarnings(True)
self.f(args)
logging.captureWarnings(False)
Run Code Online (Sandbox Code Playgroud)
这是打印警告的装饰方法:
@redirect_warnings_to_log
def tweet(message):
twt = api.PostUpdate(message)
Run Code Online (Sandbox Code Playgroud) 我正在尝试通过处理制作一个彩色方块的 3D 矩阵。它工作正常,但是当我想将其保存到序列化 DataMatrix 对象的文件时,我收到此异常:java.io.NotSerializedException。Square 和 DataMatrix 都实现了可序列化,所以我不知道是什么原因导致的。
文件管理器:
class FileManager
{
FileManager()
{}
public void saveMatrix(String path, DataMatrix dm)
{
try
{
FileOutputStream file = new FileOutputStream(path);
ObjectOutputStream output = new ObjectOutputStream(file);
output.writeObject(dm);
output.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public DataMatrix openMatrix(String path)
{
DataMatrix dm = null;
try
{
FileInputStream file = new FileInputStream(path);
ObjectInputStream input = new ObjectInputStream(file);
Object aux = input.readObject();
input.close();
if(aux instanceof DataMatrix)
{
dm = (DataMatrix)aux;
}
}
catch (EOFException …Run Code Online (Sandbox Code Playgroud)