小编Abh*_*jit的帖子

如何获取执行冻结脚本的路径

如果您运行的是冷冻python脚本从一个目录(使用py2exe冻结)和驱动从那里脚本存在不同的,什么是确定执行脚本的路径的最佳方式?

我尝试过的解决方案很少

inspect.getfile(inspect.currentframe())
Run Code Online (Sandbox Code Playgroud)

问题:不返回完整路径.它只返回脚本名称.

os.path.abspath( __file__ )
Run Code Online (Sandbox Code Playgroud)

问题:在Windows上不起作用

os.path.dirname(sys.argv[0])
Run Code Online (Sandbox Code Playgroud)

问题:返回空字符串.

os.path.abspath(inspect.getsourcefile(way3))
Run Code Online (Sandbox Code Playgroud)

如果驱动器与pwd不同,则无法工作

os.path.dirname(os.path.realpath(sys.argv[0]))
Run Code Online (Sandbox Code Playgroud)

如果驱动器与pwd不同,则无法工作

这是一个最小的不工作的例子

D:\>path
PATH=c:\Python27\;c:\Users\abhibhat\Desktop\ToBeRemoved\spam\dist\;c:\gnuwin32\bin

D:\>cat c:\Users\abhibhat\Desktop\ToBeRemoved\spam\eggs.py
import os, inspect, sys
def way1():
    return os.path.dirname(sys.argv[0])

def way2():
    return inspect.getfile(inspect.currentframe())

def way3():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

def way4():
    try:
        return os.path.abspath( __file__ )
    except NameError:
        return "Not Found"
def way5():
    return os.path.abspath(inspect.getsourcefile(way3))

if __name__ == '__main__':
    print "Path to this script is",way1()
    print "Path to this script is",way2()
    print "Path to this script is",way3()
    print "Path to this script is",way4()
    print …
Run Code Online (Sandbox Code Playgroud)

python windows path argv

9
推荐指数
1
解决办法
5322
查看次数

SEH在Linux中等效或如何处理OS信号(如SIGSERV)并继续保持

我目前正在开发一个单元测试框架,用户可以在其中创建测试用例并在框架中注册.

我还想确保如果任何用户测试代码导致崩溃,它不应该崩溃整个框架但应该被标记为失败.为了使这项工作,我编写了以下代码,以便我可以在沙盒功能中运行用户代码

bool SandBox(void *(*fn)(void *),void *arg, void *rc)
{
#ifdef WIN32
    __try
    {
        if (rc)
            rc = fn(arg);
        else
            fn(arg);
        return true;
    }
    __except (EXCEPTION_EXECUTE_HANDLER)
    {
        return false;
    }

#else
#endif
}
Run Code Online (Sandbox Code Playgroud)

这在Windows上运行得很好,但我希望我的框架是可移植的,为了这样,我想确保posix环境的类似功能.

我知道C信号处理程序可以拦截OS信号,但是将信号处理机制转换为SEH框架有一些我无法解决的挑战

  1. 即使我的程序收到信号,如何继续执行?
  2. 如何将执行控制从失败位置跳转到可以用于错误处理的块(类似于除外)?
  3. 我该如何清理资源?

另一种可能性是我在使用自己的信号处理程序在一个单独的线程上运行用户测试代码并从信号处理程序终止线程,但又不确定这是否可行.

所以在我超越之前,如果他们意识到解决这个问题/情况的更好解决方案,我希望得到社区的帮助.

c++ linux windows signals seh

9
推荐指数
1
解决办法
3416
查看次数

理解C++函数内联

我正在使用一个MS特定的关键字强制一个全局函数被内联,但我注意到如果它使用一个具有明确的简单析构函数的对象,该函数就无法内联.

引自MSDN

即使使用__forceinline,编译器也无法在所有情况下内联代码.如果出现以下情况,编译器无法内联函数:

  • 函数或其调用者使用/Ob0(调试版本的默认选项)进行编译.

  • 函数和调用者使用不同类型的异常处理(一个是C++异常处理,另一个是结构化异常处理).

  • 该函数具有可变参数列表.

  • 该函数使用内联汇编,除非编译/Og,/Ox,/O1,或/O2.

  • 该函数是递归的,没有伴随#pragma inline_recursion(on).使用pragma,递归函数被内联到16个调用的默认深度.要减少内联深度,请使用inline_depthpragma.

  • 该功能是虚拟的,虚拟调用.可以内联直接调用虚函数.

  • 程序获取函数的地址,并通过指向函数的指针进行调用.可以内联直接调用已经获取其地址的函数.

  • 该功能也标有裸__declspec修改器.

我正在尝试以下自包含程序来测试行为

#include <iostream>
#define INLINE __forceinline
template <class T>
struct rvalue
{
    T& r_;
    explicit INLINE rvalue(T& r) : r_(r) {}
};

template <class T>
INLINE
T movz(T& t)
{
    return T(rvalue<T>(t));
}
template <class T>
class Spam
{
public:
    INLINE operator rvalue<Spam>()  { return rvalue<Spam>(*this); }
    INLINE Spam() …
Run Code Online (Sandbox Code Playgroud)

c++ inlining visual-c++

9
推荐指数
1
解决办法
435
查看次数

使用qcachegrind处理profilestats输出时如何获取注释python

Kcachegrind是一个很棒的实用工具,可以在分析代码时直观地表示源代码级别的热点.在微优化我的C++代码库时,我发现它非常有用.对于我最新的python项目,我开始使用Kcachegrind处理profilestats的输出.Kcachegrind是一个仅限Linux的实用程序,但是各种非官方端口都可用,我使用的是qcachegrind.通常它在很大程度上起作用并且对于大多数问题都是足够的,除了我很难获得源注释工作.

在源标签上,我正在接受熟悉的源缺失消息

There is no source available for the following function:
   'main C:\Projects\module\src\source.py:397'
This is because no debug information is present
Recompile source and redo the profile run.
The function is located in the ELF Object:
  '(unknown)'
Run Code Online (Sandbox Code Playgroud)

使用选项

Settings -> Configure -> Source Annotation 
Run Code Online (Sandbox Code Playgroud)

并添加源基目录无用.

我有一种感觉,该实用程序需要一个与Python无关的ELF对象.在这方面的任何帮助都是有用的.

相关信息:

  • Python 2.7
  • profilestats(2.0)
  • QCachegrind 0.7.4
  • Windows 2012R2

python profiling kcachegrind python-2.7 profilestats

9
推荐指数
1
解决办法
420
查看次数

我可以使用`operator delete []`进行单个元素数组分配吗?

如果我们分配一个大小为1的对象,如下所示

int *arr = new int[1];
Run Code Online (Sandbox Code Playgroud)

我们应该使用operator delete[]或删除对象operator delete吗?

我担心的原因是编译器是否足够智能将语句转换为单个元素分配int *arr = new int,这将导致调用operator delete[]UB.

用户案例:

我有一个指针,我最终会以不同的方式分配,但最终会想要删除它.所以很想知道,对于单个元素分配,如果我一直使用,我int *arr = new int[1]可以一贯安全地使用operator delete[]

注意

能否请您回复标准以支持您的答案?

c++

8
推荐指数
2
解决办法
2808
查看次数

Lambda Capture by Value强制所有作用域对象为const

我打算用C++编写一个记忆模式,最后采用以下方法

std::function<int(int)> Memoize(std::function<int(int)> fn)
    {
        std::map<int, int> memo;
        std::function<int(int)> helper = [=](int pos) 
        {
            if (memo.count(pos) == 0)
            {
                memo[pos] = fn(pos);
            }
            return memo[pos];
        };
        return helper;
    }
Run Code Online (Sandbox Code Playgroud)

奇怪的是,我的编译器VS 2012,拒绝编译时出现以下错误

1>Source1.cpp(24): error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

在我看来,编译器故意通过值捕获所有内容作为const对象.我找不到任何有关此行为的文档参考.

任何人都可以帮助我理解这里可能发生的事情吗?

c++ lambda visual-c++ c++11

8
推荐指数
2
解决办法
521
查看次数

当`starmap`可能优于`List Comprehension`

在回答Clunky计算增量数字之间差异的问题时,是否有更美妙的方法?,我想出了两个解决方案,一个List Comprehension和另一个使用list comprehension.

对我来说,starmapSyntax看起来更清晰,可读,更简洁,更Pythonic.但仍然List Comprehension在itertools中可用,我想知道,必须有一个理由.

我的问题是什么时候There should be one-- and preferably only one --obvious way to do it.可以优先考虑LC

注意如果它是Style的问题那么它肯定是矛盾的LC

头对头比较

可读性很重要.---starmap

它再次成为一种感知问题,但对我starmap来说更具可读性operator.要使用lambda,您需要导入multi-variable,或定义itertools或显式LC功能,然而从中进行额外导入List Comprehension.

表现 ---list comprehension

>>> def using_star_map(nums):
    delta=starmap(sub,izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> def using_LC(nums):
    delta=(x-y for x,y in izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> nums=[random.randint(1,10) for …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-itertools

7
推荐指数
2
解决办法
3745
查看次数

const_cast vs reinterpret_cast

参考SO C++ FAQ 什么时候应该使用static_cast,dynamic_cast和reinterpret_cast?.

const_cast用于删除或添加const到变量,它是唯一可靠,定义和合法的方法来删除constness.reinterpret_cast用于更改类型的解释.

我理解为什么一个const变量应该只使用const_cast转换为非const,但我无法找出使用reinterpret_cast而不是const_cast来添加constness的问题的合理理由.

我知道使用reinterpret_cast甚至添加constness是不是很理智,但是使用reinterpret_cast来增加常量会是UB还是潜在的定时炸弹?

我在这里感到困惑的原因是因为声明

很大程度上,reinterpret_cast的唯一保证是,如果将结果转换回原始类型,您将得到完全相同的值.

因此,如果我使用reinterpret_cast添加constness,并且如果你将结果重新解释为原始类型,它应该返回原始类型而不应该是UB,但这违反了一个事实,即只应该使用const_cast来删除constness

在单独的注释中,该标准保证您可以使用重新解释案例添加Constness

5.2.10重新解释强制转换(7)......当"指向T1的指针"类型的prvalue v转换为"指向cv T2的指针"类型时,如果两个T1都为static_cast(static_cast(v))和T2是标准布局类型(3.9),T2的对齐要求不比T1更严格........

c++ casting const reinterpret-cast

7
推荐指数
2
解决办法
2万
查看次数

错误C4996:'std :: _ Copy_impl':带有可能不安全的参数的函数调用

我知道这个问题在SO中被多次询问过,但这与其他问题有所不同.

编译器错误:带有可能不安全的参数的函数调用

Visual Studio警告C4996

xutility(2227):警告C4996:'std :: _ Copy_impl'

失败的代码片段

DWORD dwNumberOfNames = pExportDirectory->NumberOfNames;
LPDWORD dwNames = (LPDWORD)((LPBYTE)hDLL +  pExportDirectory->AddressOfNames);
std::vector< std::string > exports;
std::copy(
    dwNames, 
    dwNames + dwNumberOfNames, 
    [&exports, &hDLL](DWORD  dwFuncOffset)
{
    std::string fname = std::string((PCHAR)((PBYTE)hDLL + dwFuncOffset));
    exports.push_back(fname);
}
);
Run Code Online (Sandbox Code Playgroud)

编译错误

错误1错误C4996:'std :: _ Copy_impl':带有可能不安全的参数的函数调用 - 此调用依赖于调用者来检查传递的值是否正确.要禁用此警告,请使用-D_SCL_SECURE_NO_WARNINGS.请参阅有关如何使用Visual C++'Checked Iterators'的文档:C:\ Program Files(x86)\ Microsoft Visual Studio 11.0\VC\include\xutility 2176

考虑到,C4996,意味着该功能已标记为已弃用问题在哪里?

  1. 它是否使用std :: copy,MS认为它是不安全的并且会被弃用?
  2. 难道是因为我用std::copyC Array
  3. 是因为我使用Lambda表达式的方式吗?
  4. 如果不推荐使用std :: copy,那么如果我需要可移植的话,还有什么选择.

注意

我知道,如何压制警告,但我很想知道,问题的根本原因是什么?

此外,同样重要的是,我知道,在不影响代码质量的情况下处理此问题的便携方式.

c++ visual-c++ c++11 visual-studio-2012

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

我们如何从成员函数返回unique_pointer成员?

我有一个带有指针成员的基类.我必须做出有根据的猜测,以确定它应该是a unique_ptr还是a shared_ptr.他们似乎都没有解决我的特定用例.

class Base
{
public:
    Base(): pInt(std::unique_ptr<int>(new int(10))) {};
    virtual std::unique_ptr<int> get() = 0;
    //Base(): pInt(std::shared_ptr<int>(new int(10))) {}; // Alternate implementation
    //virtual std::shared_ptr<int> get() = 0; // Alternate implementation
private:
    std::unique_ptr<int> pInt;
    //std::shared_ptr<int> pInt; // Alternate implementation
};
Run Code Online (Sandbox Code Playgroud)

基类已导出到Derived1Derived2.前者返回后者返回本地对象的unique_ptr成员.pIntunique_ptr

class Derived1: public Base
{
public:
    Derived1() {};
    virtual std::unique_ptr<int> get()
    {
        //return std::move(pInt);  Will compile but the ownership is lost
        return pInt;
    }
private:
    std::unique_ptr<int> pInt;
};
class …
Run Code Online (Sandbox Code Playgroud)

c++ pointers shared-ptr unique-ptr c++11

7
推荐指数
1
解决办法
1803
查看次数