所以我有一个运行循环的python脚本,它通过subprocess.Popen调用程序A等待输出,然后保存输出,然后再次调用,依此类推.(这种情况一直发生在我设置为输入的一些运行中)
问题是我有一个计时器,这样每当程序A花费超过特定的threshold_time时,脚本就会用process.kill()杀死进程并继续进行下一次迭代.
问题是,即使300次运行似乎一切正常,但有时我会收到此错误:
File "C:\Python27\lib\subprocess.py", line 1002, in terminate
_subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied
Run Code Online (Sandbox Code Playgroud)
然后脚本死了.
引用的脚本部分:
timeout = TIME_CONST
for run in runs:
killed = False
start = time.clock()
p = subprocess.Popen("SOME.CMD", cwd=r"some_dir")
# Monitor process. If it hits threshold, kill it and go to the next run
while p.poll() is None:
time.sleep(20)
secs_passed = time.clock() - start
### the following was my initial buggy line ###
#if secs_passed >= timeout:
### corrected line after jedislight's answer …Run Code Online (Sandbox Code Playgroud) 所以,我有一个包含近100,000个(键,值)对的字典,而且大多数键映射到相同的值.例如,想象一下这样的事情:
mydict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}
Run Code Online (Sandbox Code Playgroud)
我想要做的是反转字典,以便mydict中的每个值都将成为reverse_dict的一个键,并将映射到mydict上用于映射到该值的所有mydict.keys的列表.所以基于上面的例子,我会得到:
reversed_dict = {1: ['a', 'b', 'h'], 2:['e', 'c'] , 3:['d', 'j']}
Run Code Online (Sandbox Code Playgroud)
我想出了一个非常昂贵的解决方案,我真的希望听到任何比我更有效的想法.
我昂贵的解决方案
reversed_dict = {}
for value in mydict.values():
reversed_dict[value] = []
for key in mydict.keys():
if mydict[key] == value:
if key not in reversed_dict[value]: reversed_dict[value].append(key)
Output >> reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'], 3: ['d', 'j']}
Run Code Online (Sandbox Code Playgroud)
我真的很感激听到任何想法比我的更好更有效.谢谢!
I have a UserProfile model with related_name='profile' for the User FK.
Let's say I have a User obj, user1. If I want to get the UserProfile object from the user1, what is the difference between using user1.profile.all() and user1.get_profile() in terms of db hits and efficiency?