例如,这是我的目录树:
+--- test.py
|
+--- [subdir]
|
+--- another.py
Run Code Online (Sandbox Code Playgroud)
测试.py:
import os
os.system('python subdir/another.py')
Run Code Online (Sandbox Code Playgroud)
另一个.py:
import os
os.mkdir('whatever')
Run Code Online (Sandbox Code Playgroud)
运行test.py后,我预计将有一个文件夹whatever中subdir,但我得到的是:
+--- test.py
|
+--- [subdir]
| |
| +--- another.py
|
+--- whatever
Run Code Online (Sandbox Code Playgroud)
原因很明显:工作目录没有更改为subdir.那么在不同文件夹中执行.py文件时是否可以更改工作目录?笔记:
os.system只是一个例子os.system('cd XXX') 和 os.chdir不允许编辑:最后我决定使用上下文管理器,按照https://stackoverflow.com/posts/17589236/edit 中的答案
import os
import subprocess # just to call an arbitrary command e.g. 'ls'
class cd:
def __init__(self, newPath):
self.newPath = newPath
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, …Run Code Online (Sandbox Code Playgroud) AFAIK,Pythonbuiltins指的是以下中包含的异常和函数__builtins__:
>>> import builtins # import __builtin__ in Python 2
>>> dir(builtins) # dir(__builtin__) for Python 2
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
...many more...
'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed',
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',
'super', 'tuple', 'type', 'vars', 'zip']
Run Code Online (Sandbox Code Playgroud)
但看看下面的代码(Python2 和 3 都给出了相同的结果):
>>> globals()
{'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__doc__': None, '__package__': None}
>>> import threading
>>> import math
>>> globals()
{'__name__': …Run Code Online (Sandbox Code Playgroud) 有很多文章讨论价值语义与参考语义,也许更多的文章试图解释移动语义.但是,没有人谈论过值语义和移动语义之间的联系.它们是正交概念吗?
注意:这个问题不是关于比较值语义和移动语义,因为很明显这两个概念不是"可比的".这个问题是关于他们是如何联系的,特别是(如@StoryTeller所说),讨论(如何):
移动语义有助于更多地使用值类型.
我在 Windows 7 x64 上使用 pydev,我发现生成器函数中的断点被忽略(如果我注释掉yield,一切正常)。
然后我发现了一个旧的 SO question Python debugger step in generators?
答案是“我刚刚测试了 eclipse,它将在安装 pydev 的情况下进行调试。”
但是当我测试代码时,断点仍然被忽略。
def example(n):
i = 1
while i <= n:
yield i
i += 1
print "hello"
print "goodbye"
if __name__ == '__main__':
example(8)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
有类似的问题,但解决方案似乎不起作用.
说我编码了一个字符串:
>>> a = 'dada??'.encode('utf-8')
>>> type(a)
<class 'bytes'>
>>> a
>>> b'dada\xe5\xa4\xa7\xe5\xa4\xa7'
Run Code Online (Sandbox Code Playgroud)
我想要的是这样的:
dada\xe5\xa4\xa7\xe5\xa4\xa7
Run Code Online (Sandbox Code Playgroud)
str(a) 不起作用:
>>> str(a)
>>> "b'dada\\xe5\\xa4\\xa7\\xe5\\xa4\\xa7'"
Run Code Online (Sandbox Code Playgroud)
我已经尝试将stdout重定向到一个变量,但仍然,我得到了"b'dada\\xe5\\xa4\\xa7\\xe5\\xa4\\xa7'".
我可以使用正则表达式处理它并获得我想要的东西,但我正在寻找一种更加pythonic的方法来做到这一点.有什么建议?