我试图了解使用Python的库函数执行特定于操作系统的任务(例如创建文件/目录,更改文件属性等)而不仅仅通过os.system()
或执行这些命令的动机是什么subprocess.call()
?
例如,为什么我要使用os.chmod
而不是做os.system("chmod...")
?
我知道尽可能多地使用Python的可用库方法而不是直接执行shell命令更"pythonic".但是,从功能的角度来看,还有其他动机吗?
我只是在谈论在这里执行简单的单行shell命令.当我们需要更多地控制任务的执行时,我理解使用subprocess
模块更有意义,例如.
我有以下C程序:
#include <stdio.h>
int main(){
int a[2][2] = {1, 2, 3, 4};
printf("a:%p, &a:%p, *a:%p \n", a, &a, *a);
printf("a[0]:%p, &a[0]:%p \n", a[0], &a[0]);
printf("&a[0][0]:%p \n", &a[0][0]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下输出:
a:0028FEAC, &a:0028FEAC, *a:0028FEAC
a[0]:0028FEAC, &a[0]:0028FEAC
&a[0][0]:0028FEAC
Run Code Online (Sandbox Code Playgroud)
我无法理解为什么&a
,a
,*a
-所有相同.同样的a[0]
,&a[0]
和&a[0][0]
.
编辑:
感谢答案,我已经理解为什么这些价值观会相等.Kernighan&Ritchie的书中的这一行被证明是我问题的关键:
the name of an array is a synonym for the location of the initial element.
Run Code Online (Sandbox Code Playgroud)
所以,通过这个,我们得到了
a
= &a[0]
,和
a[0]
= &a[0][0]
(考虑a
作为数组的数组) …
我想了解如何__enter__
和__exit__
方法被调用文件上下文管理。
with open("test.txt") as fp:
fp.read()
Run Code Online (Sandbox Code Playgroud)
我step
在 pdb 中尝试过命令 - 而不是去定义函数open
,它只是执行它并移动到下一行。
我尝试使用sys.settrace()
过,但即使没有捕捉到的函数调用open
,__enter__
和__exit__
在任何事件。
当然,这适用于从其他模块和同一模块中导入的函数。我假设这应该以类似的方式适用于这些开箱即用的内置函数。我找不到任何指向此的文档。是否可以单步执行或跟踪内置函数的执行?
使用 Python 2.7。
我知道这const char *
是一个指向const char的指针,而是一个指向char char *const
的常量指针.我在以下代码中测试它:
const char *s = "hello"; // Not permitted to modify the string "hello"
char *const t = "world"; // Not permitted to modify the pointer t
s = "hello2"; // Valid
// t = "world2"; // Invalid, gives compilation error
// *(s + 1) = 'a'; // Invalid, gives compilation error
*(t + 1) = 'a'; // Why does this not work?
Run Code Online (Sandbox Code Playgroud)
最后一行不会给出任何错误,但会导致程序意外终止.为什么要修改t
不允许指向的字符串?
这是我的代码:
#include <set>
#include <iostream>
using namespace std;
int main(){
set<int> st;
st.insert(1);
int x = st.find(1) - st.begin();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我到了error: no match for 'operator-' in 'st.std::set<_Key, _Compare, _Alloc>::find [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>](((const int&)((const int*)(&1)))) - st.std::set<_Key, _Compare, _Alloc>::begin [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>]()'
.
我无法弄清楚迭代器差异是如何突然停止工作的!我在这里错过了什么吗?