qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
10,443,295
|
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.
I tried 'Image' to do the job but it requires 'mode' to be attributed.
I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.
But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.
Now I have two issues.
First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell
Secondly, Image.SAVE is not working properly. Following are the errors I face:
```
In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()
TypeError: 'dict' object is not callable
```
Please suggest solutions.
And please mind that the image is around 4000x4000 size array.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10443295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372149/"
] |
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
To also convert floats 0 .. 1 to uint8 s,
```
rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256
```
|
If using PIL Image convert it to array and then proceed with the below, else using matplotlib or cv2 perform directly.
```
image = cv2.imread('')[:,:,::-1]
image_2 = image[10:150,10:100]
print(image_2.shape)
img_r = image_2[:,:,0]
img_g = image_2[:,:,1]
img_b = image_2[:,:,2]
image_2 = img_r*0.2989 + 0.587*img_g + 0.114*img_b
image[10:150,10:100,0] = image_2
image[10:150,10:100,1] = image_2
image[10:150,10:100,2] = image_2
plt.imshow(image,cmap='gray')
```
|
10,443,295
|
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.
I tried 'Image' to do the job but it requires 'mode' to be attributed.
I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.
But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.
Now I have two issues.
First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell
Secondly, Image.SAVE is not working properly. Following are the errors I face:
```
In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()
TypeError: 'dict' object is not callable
```
Please suggest solutions.
And please mind that the image is around 4000x4000 size array.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10443295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372149/"
] |
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
To also convert floats 0 .. 1 to uint8 s,
```
rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256
```
|
Your distortion i believe is caused by the way you are splitting your original image into its individual bands and then resizing it again before putting it into merge;
```
`
image=Image.open("your image")
print(image.size) #size is inverted i.e columns first rows second eg: 500,250
#convert to array
li_r=list(image.getdata(band=0))
arr_r=np.array(li_r,dtype="uint8")
li_g=list(image.getdata(band=1))
arr_g=np.array(li_g,dtype="uint8")
li_b=list(image.getdata(band=2))
arr_b=np.array(li_b,dtype="uint8")
# reshape
reshaper=arr_r.reshape(250,500) #size flipped so it reshapes correctly
reshapeb=arr_b.reshape(250,500)
reshapeg=arr_g.reshape(250,500)
imr=Image.fromarray(reshaper,mode=None) # mode I
imb=Image.fromarray(reshapeb,mode=None)
img=Image.fromarray(reshapeg,mode=None)
#merge
merged=Image.merge("RGB",(imr,img,imb))
merged.show()
`
```
this works well !
|
10,443,295
|
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.
I tried 'Image' to do the job but it requires 'mode' to be attributed.
I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.
But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.
Now I have two issues.
First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell
Secondly, Image.SAVE is not working properly. Following are the errors I face:
```
In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()
TypeError: 'dict' object is not callable
```
Please suggest solutions.
And please mind that the image is around 4000x4000 size array.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10443295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372149/"
] |
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
This code doesnt create 3d array if you pass 3 channels. 2 channels remain.
|
If using PIL Image convert it to array and then proceed with the below, else using matplotlib or cv2 perform directly.
```
image = cv2.imread('')[:,:,::-1]
image_2 = image[10:150,10:100]
print(image_2.shape)
img_r = image_2[:,:,0]
img_g = image_2[:,:,1]
img_b = image_2[:,:,2]
image_2 = img_r*0.2989 + 0.587*img_g + 0.114*img_b
image[10:150,10:100,0] = image_2
image[10:150,10:100,1] = image_2
image[10:150,10:100,2] = image_2
plt.imshow(image,cmap='gray')
```
|
10,443,295
|
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.
I tried 'Image' to do the job but it requires 'mode' to be attributed.
I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.
But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.
Now I have two issues.
First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell
Secondly, Image.SAVE is not working properly. Following are the errors I face:
```
In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()
TypeError: 'dict' object is not callable
```
Please suggest solutions.
And please mind that the image is around 4000x4000 size array.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10443295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372149/"
] |
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
To also convert floats 0 .. 1 to uint8 s,
```
rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256
```
|
I don't really understand your question but here is an example of something similar I've done recently that seems like it might help:
```
# r, g, and b are 512x512 float arrays with values >= 0 and < 1.
from PIL import Image
import numpy as np
rgbArray = np.zeros((512,512,3), 'uint8')
rgbArray[..., 0] = r*256
rgbArray[..., 1] = g*256
rgbArray[..., 2] = b*256
img = Image.fromarray(rgbArray)
img.save('myimg.jpeg')
```
I hope that helps
|
10,443,295
|
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.
I tried 'Image' to do the job but it requires 'mode' to be attributed.
I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.
But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.
Now I have two issues.
First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell
Secondly, Image.SAVE is not working properly. Following are the errors I face:
```
In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()
TypeError: 'dict' object is not callable
```
Please suggest solutions.
And please mind that the image is around 4000x4000 size array.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10443295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372149/"
] |
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
To also convert floats 0 .. 1 to uint8 s,
```
rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256
```
|
```
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
```
This code doesnt create 3d array if you pass 3 channels. 2 channels remain.
|
58,642,357
|
I am trying to automate the login to the following page using selenium:
<https://services.cal-online.co.il/Card-Holders/SCREENS/AccountManagement/Login.aspx?ReturnUrl=%2fcard-holders%2fScreens%2fAccountManagement%2fHomePage.aspx>
Trying to find the elements of username and password using both id, css selector and xpath didn't work.
```
self._web_driver.find_element_by_xpath('//*[@id="txt-login-username"]')
self._web_driver.find_element_by_id("txt-login-password")
self._web_driver.find_element_by_css_selector('#txt-login-username')
```
For all three I get NoSuchElement exception
I tried the following JS script: `document.getElementById('txt-login-username')`
when I run this script in selenium or in firefox it returns Null
but when I run it in chrome console I get a result I can use.
Is there any way to make it work from the python code or to run this on the chrome console itself and not from the python execute\_script?
|
2019/10/31
|
[
"https://Stackoverflow.com/questions/58642357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9608607/"
] |
To automate the login to the [page](https://services.cal-online.co.il/Card-Holders/SCREENS/AccountManagement/Login.aspx?ReturnUrl=%2fcard-holders%2fScreens%2fAccountManagement%2fHomePage.aspx) using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) as the the desired elements are within an `<iframe>` so you have to:
* Induce *WebDriverWait* for the desired *frame to be available and switch to it*.
* Induce *WebDriverWait* for the desired *element to be clickable*.
* You can use the following solution:
+ Code Block:
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://services.cal-online.co.il/Card-Holders/SCREENS/AccountManagement/Login.aspx?ReturnUrl=%2fcard-holders%2fScreens%2fAccountManagement%2fHomePage.aspx")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='calconnectIframe']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='txt-login-username']"))).send_keys("ariel6653")
driver.find_element_by_xpath("//input[@id='txt-login-password']").send_keys("ariel6653")
```
Browser Snapshot:
[](https://i.stack.imgur.com/DJ6PV.png)
>
> Here you can find a relevant discussion on [Ways to deal with #document under iframe](https://stackoverflow.com/questions/53203417/ways-to-deal-with-document-under-iframe)
>
>
>
|
found a solution to the problem. the problem really was that the object is inside an iframe.
I tried to use the solution suggested in [Get element from within an iFrame](https://stackoverflow.com/questions/1088544/get-element-from-within-an-iframe)
but got a security error. the solution is to switch frame the follwoing way:
`driver.switch_to.frame("iframe")`
and now you can use the normal find elment
|
29,574,698
|
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.
```
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
```
When run in python 3 it returns the following error message:
```
TypeError: Can't convert 'int' object to str implicitly
```
What changes can I make to make this compatible with python 3?
|
2015/04/11
|
[
"https://Stackoverflow.com/questions/29574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776196/"
] |
You could try the `.clip()` function. You can use `.save()` to save the state to `.restore()` after the clip so it isn't destructive. You can set the path to whatever you would like and it will create a vector mask of that shape.
```
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
context.save();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(0, 100);
context.lineTo(70, 200);
context.lineTo(100, 0);
context.closePath();
context.clip();
context.drawImage(img, 0, 0);
context.restore();
}
img.src = "https://www.noao.edu/image_gallery/images/d2/m51-400.jpg";
```
[See Fiddle here](http://jsfiddle.net/p7b0qasm/2/).
|
Try something like this
```
context.fillStyle = "rgba(255, 255, 255, 1)";
context.fillRect(0, 100, 400, 400);
context.fillStyle = "rgba(255, 255, 255, 1)";
context.fillRect(100, 0, 400, 400);
```
<http://jsfiddle.net/xqzxawyb/1/>
|
29,574,698
|
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.
```
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
```
When run in python 3 it returns the following error message:
```
TypeError: Can't convert 'int' object to str implicitly
```
What changes can I make to make this compatible with python 3?
|
2015/04/11
|
[
"https://Stackoverflow.com/questions/29574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776196/"
] |
If your "complex shape" is defined in a path command (like the square path command in your example--only your path is more complex), then you can use compositing to eliminate all but the pixels inside the path:
(1) Define your path and fill it with a solid color,
(2) Set compositing to source-in which will draw new pixels only where existing solid pixels are present and everything else is made transparent.
```
context. globalCompositeOperation='source-in';
```
(3) draw your starfield image. The image will appear only inside the path--everything else will be transparent.
Here's example code and a Demo:
```js
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/water.jpg";
function start(){
var points=[];
points.push({x:150,y:0});
points.push({x:200,y:100});
points.push({x:250,y:100});
points.push({x:225,y:150});
points.push({x:250,y:200});
points.push({x:100,y:200});
points.push({x:150,y:0});
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=0;i<points.length;i++){
ctx.lineTo(points[i].x,points[i].y);
}
ctx.closePath();
ctx.fill()
ctx.globalCompositeOperation='source-in'
ctx.drawImage(img,0,0);
}
```
```css
body{ background-color: ivory; }
#canvas{border:1px solid red;}
```
```html
<canvas id="canvas" width=300 height=300></canvas>
```
|
Try something like this
```
context.fillStyle = "rgba(255, 255, 255, 1)";
context.fillRect(0, 100, 400, 400);
context.fillStyle = "rgba(255, 255, 255, 1)";
context.fillRect(100, 0, 400, 400);
```
<http://jsfiddle.net/xqzxawyb/1/>
|
29,574,698
|
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.
```
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
```
When run in python 3 it returns the following error message:
```
TypeError: Can't convert 'int' object to str implicitly
```
What changes can I make to make this compatible with python 3?
|
2015/04/11
|
[
"https://Stackoverflow.com/questions/29574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776196/"
] |
You could try the `.clip()` function. You can use `.save()` to save the state to `.restore()` after the clip so it isn't destructive. You can set the path to whatever you would like and it will create a vector mask of that shape.
```
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
context.save();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(0, 100);
context.lineTo(70, 200);
context.lineTo(100, 0);
context.closePath();
context.clip();
context.drawImage(img, 0, 0);
context.restore();
}
img.src = "https://www.noao.edu/image_gallery/images/d2/m51-400.jpg";
```
[See Fiddle here](http://jsfiddle.net/p7b0qasm/2/).
|
```
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #d3d3d3;">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(0,0,100,100);
ctx.stroke();
```
DEMO : <http://jsfiddle.net/q776zjdx/>
|
29,574,698
|
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.
```
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
```
When run in python 3 it returns the following error message:
```
TypeError: Can't convert 'int' object to str implicitly
```
What changes can I make to make this compatible with python 3?
|
2015/04/11
|
[
"https://Stackoverflow.com/questions/29574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776196/"
] |
If your "complex shape" is defined in a path command (like the square path command in your example--only your path is more complex), then you can use compositing to eliminate all but the pixels inside the path:
(1) Define your path and fill it with a solid color,
(2) Set compositing to source-in which will draw new pixels only where existing solid pixels are present and everything else is made transparent.
```
context. globalCompositeOperation='source-in';
```
(3) draw your starfield image. The image will appear only inside the path--everything else will be transparent.
Here's example code and a Demo:
```js
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/water.jpg";
function start(){
var points=[];
points.push({x:150,y:0});
points.push({x:200,y:100});
points.push({x:250,y:100});
points.push({x:225,y:150});
points.push({x:250,y:200});
points.push({x:100,y:200});
points.push({x:150,y:0});
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=0;i<points.length;i++){
ctx.lineTo(points[i].x,points[i].y);
}
ctx.closePath();
ctx.fill()
ctx.globalCompositeOperation='source-in'
ctx.drawImage(img,0,0);
}
```
```css
body{ background-color: ivory; }
#canvas{border:1px solid red;}
```
```html
<canvas id="canvas" width=300 height=300></canvas>
```
|
```
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #d3d3d3;">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(0,0,100,100);
ctx.stroke();
```
DEMO : <http://jsfiddle.net/q776zjdx/>
|
29,574,698
|
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.
```
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
```
When run in python 3 it returns the following error message:
```
TypeError: Can't convert 'int' object to str implicitly
```
What changes can I make to make this compatible with python 3?
|
2015/04/11
|
[
"https://Stackoverflow.com/questions/29574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776196/"
] |
You could try the `.clip()` function. You can use `.save()` to save the state to `.restore()` after the clip so it isn't destructive. You can set the path to whatever you would like and it will create a vector mask of that shape.
```
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
context.save();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(0, 100);
context.lineTo(70, 200);
context.lineTo(100, 0);
context.closePath();
context.clip();
context.drawImage(img, 0, 0);
context.restore();
}
img.src = "https://www.noao.edu/image_gallery/images/d2/m51-400.jpg";
```
[See Fiddle here](http://jsfiddle.net/p7b0qasm/2/).
|
If your "complex shape" is defined in a path command (like the square path command in your example--only your path is more complex), then you can use compositing to eliminate all but the pixels inside the path:
(1) Define your path and fill it with a solid color,
(2) Set compositing to source-in which will draw new pixels only where existing solid pixels are present and everything else is made transparent.
```
context. globalCompositeOperation='source-in';
```
(3) draw your starfield image. The image will appear only inside the path--everything else will be transparent.
Here's example code and a Demo:
```js
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/water.jpg";
function start(){
var points=[];
points.push({x:150,y:0});
points.push({x:200,y:100});
points.push({x:250,y:100});
points.push({x:225,y:150});
points.push({x:250,y:200});
points.push({x:100,y:200});
points.push({x:150,y:0});
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=0;i<points.length;i++){
ctx.lineTo(points[i].x,points[i].y);
}
ctx.closePath();
ctx.fill()
ctx.globalCompositeOperation='source-in'
ctx.drawImage(img,0,0);
}
```
```css
body{ background-color: ivory; }
#canvas{border:1px solid red;}
```
```html
<canvas id="canvas" width=300 height=300></canvas>
```
|
68,402,859
|
I am using python API to save and download model from MinIO. This is a MinIO installed on my server. The data is in binary format.
```
a = 'Hello world!'
a = pickle.dumps(a)
client.put_object(
bucket_name='my_bucket',
object_name='my_object',
data=io.BytesIO(a),
length=len(a)
)
```
I can see object saved through command line :
```
mc cat origin/my_bucket/my_object
Hello world!
```
However, when i try to get it through Python API :
```
response = client.get_object(
bucket_name = 'my_bucket',
object_name= 'my_object'
)
```
response is a urllib3.response.HTTPResponse object here.
I am trying to read it as :
```
response.read()
b''
```
I get a blank binary string. How can I read this object? It won't be possible for me to know its length at the time of reading it.
and here is `response.__dict__` :
{'headers': HTTPHeaderDict({'Accept-Ranges': 'bytes', 'Content-Length': '27', 'Content-Security-Policy': 'block-all-mixed-content', 'Content-Type': 'application/octet-stream', 'ETag': '"75687-1"', 'Last-Modified': 'Fri, 16 Jul 2021 14:47:35 GMT', 'Server': 'MinIO/DEENT.T', 'Vary': 'Origin', 'X-Amz-Request-Id': '16924CCA35CD', 'X-Xss-Protection': '1; mode=block', 'Date': 'Fri, 16 Jul 2021 14:47:36 GMT'}), 'status': 200, 'version': 11, 'reason': 'OK', 'strict': 0, 'decode\_content': True, 'retries': Retry(total=5, connect=None, read=None, redirect=None, status=None), 'enforce\_content\_length': False, 'auto\_close': True, '\_decoder': None, '\_body': None, '\_fp': <http.client.HTTPResponse object at 01e50>, '\_original\_response': <http.client.HTTPResponse object at 0x7e50>, '\_fp\_bytes\_read': 0, 'msg': None, '\_request\_url': None, '\_pool': <urllib3.connectionpool.HTTPConnectionPool object at 0x790>, '\_connection': None, 'chunked': False, 'chunk\_left': None, 'length\_remaining': 27}
|
2021/07/16
|
[
"https://Stackoverflow.com/questions/68402859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797308/"
] |
Try with response.data.decode()
|
The response is a `urllib3.response.HTTPResponse` object.
See [urllib3 Documentation](https://urllib3.readthedocs.io/en/latest/reference/urllib3.response.html):
>
> Backwards-compatible with http.client.HTTPResponse but the response body is loaded and decoded on-demand when the data property is accessed.
>
>
>
Specifically, you should read the answer like this:
```py
response.data # len(response.data)
```
Or, if you want to stream the object, you have examples on the `minio-py` repository: [examples/get\_objects](https://github.com/minio/minio-py/blob/release/examples/get_object.py).
|
45,406,332
|
I am very new to SQLAlchemy. I am having some difficulty setting up a one to many relationship between two models in my application. I have two models User `Photo'. A user has only one role associated with it and a role has many users associated with it.
This is the code that I have in my data\_generator.py file:
```
# coding=utf-8
from sqlalchemy import Column, Integer, String, BigInteger,Date, Enum, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
import time
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
import datetime
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer(), primary_key=True)
username = Column(String(30), unique=True, nullable=False)
password = Column(String, default='123456', nullable=False)
name = Column(String(30), nullable=False)
grade = Column(String(30))
emp_no = Column(BigInteger, unique=True, nullable=False)
roles = relationship('Role', back_populates='users')
class Scene(Base):
__tablename__ = 'scenes'
id = Column(Integer, primary_key=True)
scene_name = Column(String(30), nullable=False)
life_time = Column(Date, nullable=False,
default=datetime.datetime.strptime(
time.strftime("%Y-%m-%d", time.localtime(time.time() + (12 * 30 * 24 * 3600))),'%Y-%m-%d').date())
scene_description = Column(String(150), default="")
class Gateway(Base):
__tablename__ = 'gateways'
id = Column(Integer, primary_key=True)
gateway_name = Column(String(30), nullable=False)
gateway_api_key = Column(String(100), nullable=False, unique=True)
gateway_type = Column(Enum('up', 'down', 'soft', name="gateway_type"), nullable=False)
class Role(Base):
__tablename__ = 'roles'
id = Column(Integer, primary_key=True)
role_name = Column(String(30), unique=True, nullable=False)
users = relationship('User', back_populates='roles')
def __repr__(self):
return self.role_name
engine = create_engine('sqlite:///memory:')
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
Base.metadata.create_all(engine)
ed_user = User(name='ed', username='jack', password='123', emp_no=1, grade='1', roles=1)
example_scene = Scene(scene_name='example_1', scene_description='example_description')
example_gateway = Gateway(gateway_name='example_1',gateway_api_key='11111',gateway_type='up')
# session.add(example_gateway)
# session.commit()
def init_user(flag, number):
while number >= 1:
if flag == 1:
ed_user = User(name='ed', username='jack', password='123', emp_no=1, grade='1')
pass
if flag == 2:
# TODO admin
pass
if flag == 3:
# TODO teacher
pass
number -= 1
def init_scene(number):
while number >= 1:
number -= 1
# TODO scene
def init_gateway(api_key, number):
# TODO gateway
pass
if __name__ == '__main__':
with session.no_autoflush:
c = session.query(Gateway).all()
print c[0].id
```
The error that I keep encountering is shown below:
```
/usr/bin/python2.7 /home/pajamas/PycharmProjects/untitled5/data_generator.py
Traceback (most recent call last):
File "/home/pajamas/PycharmProjects/untitled5/data_generator.py", line 73, in <module>
ed_user = User(name='ed', username='jack', password='123', emp_no=1, grade='1', roles=1)
File "<string>", line 2, in __init__
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 347, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 764, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 177, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
fn(*args, **kw)
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 3088, in _event_on_first_init
configure_mappers()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2984, in configure_mappers
mapper._post_configure_properties()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1810, in _post_configure_properties
prop.init()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 184, in init
self.do_init()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1658, in do_init
self._setup_join_conditions()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1733, in _setup_join_conditions
can_be_synced_fn=self._columns_are_mapped
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1991, in __init__
self._determine_joins()
File "/home/pajamas/.local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 2096, in _determine_joins
"specify a 'primaryjoin' expression." % self.prop)
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.roles - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
Process finished with exit code 1
```
Can someone assist me with this? Help would be greatly appreciated.
|
2017/07/31
|
[
"https://Stackoverflow.com/questions/45406332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7954998/"
] |
There might be three relationships between User and Role:
* One to One(One user has only one Role)
* Many to One(One user has many roles)
* Many to Many(Many user has many roles)
For One to One:
```
class Role(Base):
id = Column(Integer, primary_key=True)
# ...
user_id = Column(Integer, ForeignKey("user.id"))
class User(Base):
id = Column(Integer, primary_key=True)
# ...
role = relationship("Role", back_populates="user", uselist=False)
```
For Many to One:
```
class Role(Base):
id = Column(Integer, primary_key=True)
# ...
user_id = Column(Integer, ForeignKey("user.id"))
class User(Base):
id = Column(Integer, primary_key=True)
# ...
roles = relationship("Role", back_populates="user")
```
For Many to Many:(In this relation, we need a associate table)
```
roles_users = Table("roles_users",
Column("role_id", Integer, ForeignKey("role.id")),
Column("user_id", Integer, ForeignKey("user.id")))
class Role(Base):
id = Column(Integer, primary_key=True)
# ...
class User(Base):
id = Column(Integer, primary_key=True)
# ...
roles = relationship("Role", back_populates="users", secondary=roles_users)
```
|
I made a low-level mistake because of my lack of database and SQL alchemy.
First of all, this is a typical "one to many" problem.Relationship connects two rows from two tables by users' foreign key. The role\_id is defined as the foreign key, which builds the connections.
The parameter "roles.id" in "ForeignKey()" clarified this column is the id of Role's rows.
relationship() 's backref specialized the role model.
|
10,213,509
|
I have a **Django** site, hosted on **Heroku**.
One of the models has an image field, that takes uploaded images, resizes them, and pushes them to Amazon S3 so that they can be stored persistently.
This is working well, using **PIL**
```
def save(self, *args, **kwargs):
# Save this one
super(Product, self).save(*args,**kwargs)
# resize on file system
size = 200, 200
filename = str(self.thumbnail.path)
image = Image.open(filename)
image.thumbnail(size, Image.ANTIALIAS)
image.save(filename)
# send to amazon and remove from ephemeral file system
if put_s3(filename):
os.remove(filename)
return True
```
However, PIL seems to work fine for PNGs and GIFs, but is not compliled with **libjpeg**. On a local development environment or a fully controlled 'nix server, it is simply a case of installing the jpeg extension.
But does anyone know whether Jpeg manipulation is possible using the Cedar Heroku stack? Is there something else that can be added to requirements.txt?
Among other unrelated packages, the requirements.txt for this virtualenv includes:
```
Django==1.3.1
PIL==1.1.7
distribute==0.6.24
django-queued-storage==0.5
django-storages==1.1.4
psycopg2==2.4.4
python-dateutil==1.5
wsgiref==0.1.2
```
Thanks
|
2012/04/18
|
[
"https://Stackoverflow.com/questions/10213509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267757/"
] |
I use this PIL fork in requirements.txt:
```
-e hg+https://bitbucket.org/etienned/pil-2009-raclette/#egg=PIL
```
and can use JPEG without issues:
```
--------------------------------------------------------------------
PIL 1.2a0 SETUP SUMMARY
--------------------------------------------------------------------
version 1.2a0
platform Python 2.7.2 (default, Oct 31 2011, 16:22:04)
[GCC 4.4.3] on linux2
--------------------------------------------------------------------
*** TKINTER support not available
--- JPEG support available
*** WEBP support not available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
--- LITTLECMS support available
--------------------------------------------------------------------
```
|
Also please consider using [Pillow](https://pypi.python.org/pypi/Pillow), the "friendly" PIL fork which offers:
* Setuptools compatibility
* Python 3 compatibility
* Frequent release cycle
* Many bug fixes
|
25,433,921
|
I need to run this file:
```
from apps.base.models import Event
from apps.base.models import ProfileActiveUntil
from django.template import Context
from django.db.models import Q
import datetime
from django.core.mail import EmailMultiAlternatives
from bonzer.settings import SITE_HOST
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from bonzer.settings import send_mail, BONZER_MAIL, BONZER_MAIL_SMTP, BONZER_MAIL_USER, BONZER_MAIL_PASS, BONZER_MAIL_USETLS
today = datetime.date.today()
monthAgo = today + datetime.timedelta(days=1)
monthAgoMinusOneDay = today + datetime.timedelta(days=2)
events = Event.objects.all()
ProfileActiveUntils = ProfileActiveUntil.objects.filter(Q(active_until__range=(monthAgo, monthAgoMinusOneDay)))
msg = MIMEMultipart('alternative')
msg['Subject'] = "Novim dogodivscinam naproti"
msg['From'] = BONZER_MAIL
msg['To'] = 'jjag3r@gmail.com'
text = u'bla'
html = u'bla'
send_mail(msg_to=msg['To'], msg_subject=msg['Subject'], msg_html=html, msg_text=text)
```
I execute it like this: `*/2 * * * * /usr/local/bin/python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.py`
But I get error: No module named apps.base.models.
Important fact is that I can't install virtualenv on server because I don't have permissions. Also I'm kind of newbie on this stuff so I don't have a lot of skills on servers or python.
Thank you.
|
2014/08/21
|
[
"https://Stackoverflow.com/questions/25433921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216697/"
] |
`cron` does not read rc shell files so you need to define the enviroment variable PYTHONPATH to include the location of the `apps` package and all other module files that are required by the script.
```
PYTHONPATH=/usr/local/lib/python2.7:/usr/lib/python2.7
*/2 * * * * /usr/local/bin/python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.pyr
```
|
I would assume this is a problem with your cwd (current working directory). An easy way to test this would be to go to the root (cd /) then run:
```
python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.py
```
You should get the same error. The path you will want to use will depend on the place where you normally run the script from. I would guess it would either be:
/home/nezap/webapps/bonzer/bonzer/apps/base
or
/home/nezap/webapps/bonzer/bonzer/
So your solution would either be:
```
*/2 * * * * cd /home/nezap/webapps/bonzer/bonzer/apps/base && /usr/local/bin/python2.7 ./alert.py
```
or
```
*/2 * * * * cd /home/nezap/webapps/bonzer/bonzer && /usr/local/bin/python2.7 ./apps/base/alert.py
```
basically you are telling cron to change directory to that path, then if that works(the &&) run the following command.
|
25,496,012
|
The answers to [this question](https://stackoverflow.com/questions/14043886/python-2-3-convert-integer-to-bytes-cleanly) make it seem like there are two ways to convert an integer to a `bytes` object in Python 3. They show
`s = str(n).encode()`
and
```
n = 5
bytes( [n] )
```
Being the same. However, testing that shows the values returned are different:
```
print(str(8).encode())
#Prints b'8'
```
but
```
print(bytes([8])) #prints b'\x08'
```
I know that the first method changes the `int 8` into a string (`utf-8` I believe) which has the hex value of 56, but what does the second one print? Is that just the hex value of 8? (a `utf-8` value of backspace?)
Similarly, are both of these one byte in size? It seems like the second one has two characters == two bytes but I could be wrong there...
|
2014/08/25
|
[
"https://Stackoverflow.com/questions/25496012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291506/"
] |
Those two examples are *not* equivalent. `str(n).encode()` takes whatever you give it, turns it into its string representation, and then encodes using a character codec like utf8. `bytes([..])` will form a bytestring with the byte values of the array given. The representation `\xFF` is in fact the hexadecimal representation of a *single* byte value.
```
>>> str(8).encode()
b'8'
>>> b'8' == b'\x38'
True
```
|
`b'8'` is a `bytes` object which contains a single byte with value of the character `'8'` which is equal to `56`.
`b'\x08'` is a `bytes` object which contains a single byte with value `8`, which is the same as `0x8`.
|
30,637,387
|
I'm running Notebook server on remote machine and want to somehow protect it. Unfortunately I cannot use password authentication (because if I do so then I can't use `ein`, an emacs package for ipython notebooks).
The other obvious solution is to make IPython Notebook accept connections only from my local machine's ip, but it seems that there is no regular way to do this with ipython configs. Maybe I'm missing something?
Or maybe there is another way to achieve my goal?
UPDATE: here's a bug about it posted to EIN tracker: <https://github.com/millejoh/emacs-ipython-notebook/issues/57>.
UPDATE2: thanks to millejoh (`ein` developer), now `ein` should work with password-protected notebooks, so the question is not actual anymore. Thanks everyone for your replies!
|
2015/06/04
|
[
"https://Stackoverflow.com/questions/30637387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2500596/"
] |
You can set the port for iPython to a port that will only be used by iPython.
And then restrict access to that port to only you local machine's IP.
To set the port:
Edit the ipython\_notebook\_config.py file and insert or edit the line:
```
c.NotebookApp.port = 7777
```
where you change 7777 to the port of your choice.
Assuming the remote machine in Linux. You can then use iptables to block access to that port except from your local machine:
```
iptables -I INPUT \! --src 1.2.3.4 -m tcp -p tcp --dport 7777 -j DROP # if it's not 1.2.3.4, drop it
```
where you change 1.2.3.4 to your local ip and 7777 to the port you have iPython working on.
Sources:
For iPython configs: [Docs](http://ipython.org/ipython-doc/1/interactive/public_server.html)
For blocking IPs : [StackExchange](https://serverfault.com/questions/146569/iptables-how-to-allow-only-one-ip-through-specific-port) [cyberciti](http://www.cyberciti.biz/tips/linux-iptables-6-how-to-block-outgoing-access-to-selectedspecific-ip-address.html)
|
I dont found anything about other authentication way on ipython website, then you can have right.
Here <http://ipython.org/ipython-doc/3/notebook/security.html> is something about ipython trust. Maybe it will be sufficient for you.
|
56,476,940
|
I have successfully installed z3 on a remote server where I am not root. when I try to run my python code I get :
```
ModuleNotFoundError: No module named 'z3'
```
I understand that I have to add it to PYTHONPATH in order to work and so I went ahead and done that like this:
>
> export PYTHONPATH=$HOME/usr/lib/python-2.7/site-packages:$PYTHONPATH
>
>
>
I still get the same issue though, how can I verify that it was correctly added to the variables environment? what am i doing wrong?
|
2019/06/06
|
[
"https://Stackoverflow.com/questions/56476940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10881142/"
] |
Did you pass the `--python` flag when you called `scripts/mk_make.py`?
See the instructions on <https://github.com/Z3Prover/z3/blob/master/README.md> on how to exactly enable Python (about all the way down in that page). Here's an example invocation:
```
python scripts/mk_make.py --prefix=/home/leo --python --pypkgdir=/home/leo/lib/python-2.7/site-packages
```
Change the directories appropriately, of course.
|
For Windows users that just downloaded and unzipped the compiled Z3 binary into some arbitrary directory, adding the location of the python directory in the directory where Z3 was installed to PYTHONPATH did the trick. ie in Cygwin : `$ export PYTHONPATH=<location of z3>/bin/python:$PYTHONPATH` (or the equivalent in a Windows command shell)
|
43,168,078
|
I am trying to extract how many songs are release in every year from csv. my data looks like this
```
no,artist,name,year
"1","Bing Crosby","White Christmas","1942"
"2","Bill Haley & his Comets","Rock Around the Clock","1955"
"3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554"
"4","Celine Dion","My Heart Will Go On","1998","35.405"
"5","Bryan Adams","(Everything I Do) I Do it For You","1991"
"6","The Beatles","Hey Jude","1968"
"7","Whitney Houston","I Will Always Love You","1992","34.560"
"8","Pink Floyd","Another Brick in the Wall (part 2)","1980"
"9","Irene Cara","Flashdance... What a Feeling","1983"
"10","Elton John","Candle in the Wind '97","1992"
```
my files consists of 3000 lines data with additional fields but i am interested to extract how many songs are released in every year
i tried to extract the year and songs and my code is here, but I am new in python and therefore I don't know how to solve my problem. my code is
```
from itertools import islice
import csv
filename = '/home/rob/traintask/top3000songs.csv'
data = csv.reader(open(filename))
# Read the column names from the first line of the file
fields = data.next()[3] // I tried to read the year columns
print fields
count = 0
for row in data:
# Zip together the field names and values
items = zip(fields, row)
item = {} \\ here I am lost, i think i should make a dict and set year as key and no of songs as values, but I don't know how to do it
# Add the value to our dictionary
for (name, value) in items:
item[name] = value.strip()
print 'item: ', item
```
I am doing it completely wrong. but If somebody give me some hints or help that how i can count no of songs released in a year. i will be thankful.
|
2017/04/02
|
[
"https://Stackoverflow.com/questions/43168078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7438144/"
] |
2 very simple lines of code:
```
import pandas as pd
my_csv=pd.read_csv(filename)
```
and to get the number of songs per year:
```
songs_per_year= my_csv.groupby('year')['name'].count()
```
|
You can use a `Counter` object from the [`collections`](https://docs.python.org/2/library/collections.html) module..
```
>>> from collections import Counter
>>> from csv import reader
>>>
>>> YEAR = 3
>>> with open('file.txt') as f:
... next(f, None) # discard header
... year2rel = Counter(int(line[YEAR]) for line in reader(f))
...
>>> year2rel
Counter({1992: 2, 1942: 2, 1955: 1, 1990: 1, 1991: 1, 1968: 1, 1980: 1, 1983: 1})
```
|
70,946,840
|
Is it possible to make a dot function that is var.function() that changes var? I realise that i can do:
```
class Myclass:
def function(x):
return 2
Myclass.function(1):
```
But i want to change it like the default python function.
```
def function(x):
return(3)
x=1
x.function()
print(x)
```
and it returns
```
>>> 3
```
|
2022/02/01
|
[
"https://Stackoverflow.com/questions/70946840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18093990/"
] |
You can use Pandas `.shift()` to compare the values of the series with the next row, build up a session value based on the "hops", and then group by that session value.
```
import pandas as pd
df = pd.DataFrame({
'name' : ['John', 'John', 'John', 'John', 'John', 'Emily', 'Emily', 'John'],
'app' : ['Excel','Excel','Spotify','Excel','Spotify','Excel', 'Excel', 'Excel'],
'duration':[3,2,1,1,2,4,1,3]})
session = ((df.name != df.name.shift()) | (df.app != df.app.shift())).cumsum()
df2 = df.groupby(['name', 'app', session], as_index=False, sort=False)['duration'].sum()
print(df2)
```
Output:
```
name app duration
0 John Excel 5
1 John Spotify 1
2 John Excel 1
3 John Spotify 2
4 Emily Excel 5
5 John Excel 3
```
|
One solution would be to add a column to define hops. Then group by that column
```
hop_id = 1
for i in df.index:
df.loc[i,'hop_id'] = hop_id
if (df.loc[i,'Name']!= df.loc[i+1,'Name']) or (df.loc[i,'Application'] != df.loc[i+1,'Application']):
hop_id = hop_id +1
df.groupby('hop_id')['Duration'].sum()
```
|
67,415,482
|
I created a Sudoku class in python, I want to solve the board and also keep an instance variable with the original board, but when I use the `solve()` method which uses the recursive backtracking algorithm `self.board` changes together with `self.solved_board` why is that, and how can I keep a variable with the original copy?
```
grid = [ [3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0] ]
class Sudoku:
def __init__(self, board):
self.board = board
self.solved_board = board[:] #<--- I used the [:] because I thought this will create a new list
def get_board(self):
return self.board
def set_board(self, board):
self.board = board
self.solved_board = board
def print_original_board(self):
self.print(self.board)
def print_solved_board(self):
self.print(self.solved_board)
def print(self, board):
"""Receiving a matrix and printing a board with seperation"""
for i in range(len(board)):
if i % 3 == 0 and i!=0:
print('---------------------------------')
for j in range(len(board[i])):
if j%3==0 and j!=0:
print(" | ", end='')
print(" " + str(board[i][j]) + " ", end='')
print('')
def find_empty(self,board):
"""Receiving a matrix, loops through it, and return a tuple
with the row and the column of the free stop in the matrix"""
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==0:
return (i,j)
return None
def is_valid(self, board, num, pos):
"""Receiving matrix, a number we want to insert, and a tuple with the row and col
and will check if the row, col, and box are valid so we can place the number
in the position"""
# Check row
for i in range(len(board[pos[0]])):
if pos[0] != i and board[pos[0]][i] == num:
return False
# Check col
for i in range(len(board)):
if pos[1] != i and board[i][pos[1]] == num:
return False
pos_row = pos[0] // 3
pos_col = pos[1] // 3
for i in range(pos_row*3 ,pos_row*3 + 3):
for j in range(pos_col * 3, pos_col*3 + 3):
if (i,j) != pos and board[i][j] == num:
return False
return True
def solve(self):
"""Using backtracking algorithm to solve the solved_board variable"""
find = self.find_empty(self.solved_board)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if(self.is_valid(self.solved_board, i, (row, col))):
self.solved_board[row][col] = i
if self.solve():
return self.solved_board
self.solved_board[row][col] = 0
return False
sudoku = Sudoku(grid)
sudoku.print_original_board()
print(" ")
sudoku.solve()
sudoku.print_original_board() # <---- This prints the solved board
```
|
2021/05/06
|
[
"https://Stackoverflow.com/questions/67415482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7311644/"
] |
`self.solved_board = board[:]` does indeed create a new list, but it references the same inner lists as `board`. You need to go one level deeper:
```
self.solved_board = [row[:] for row in board]
```
|
Yeah, `board[:]` does create a new list -- of all those old inner lists:
```py
In [23]: board = [[1], [2]]
In [24]: board2 = board[:]
In [25]: board2[0] is board[0]
Out[25]: True
In [26]: board2[0][0] += 10
In [28]: board
Out[28]: [[11], [2]]
```
You'd need to deepcopy it; e.g.,
```py
solved_board = [row[:] for row in board]
```
|
67,415,482
|
I created a Sudoku class in python, I want to solve the board and also keep an instance variable with the original board, but when I use the `solve()` method which uses the recursive backtracking algorithm `self.board` changes together with `self.solved_board` why is that, and how can I keep a variable with the original copy?
```
grid = [ [3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0] ]
class Sudoku:
def __init__(self, board):
self.board = board
self.solved_board = board[:] #<--- I used the [:] because I thought this will create a new list
def get_board(self):
return self.board
def set_board(self, board):
self.board = board
self.solved_board = board
def print_original_board(self):
self.print(self.board)
def print_solved_board(self):
self.print(self.solved_board)
def print(self, board):
"""Receiving a matrix and printing a board with seperation"""
for i in range(len(board)):
if i % 3 == 0 and i!=0:
print('---------------------------------')
for j in range(len(board[i])):
if j%3==0 and j!=0:
print(" | ", end='')
print(" " + str(board[i][j]) + " ", end='')
print('')
def find_empty(self,board):
"""Receiving a matrix, loops through it, and return a tuple
with the row and the column of the free stop in the matrix"""
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==0:
return (i,j)
return None
def is_valid(self, board, num, pos):
"""Receiving matrix, a number we want to insert, and a tuple with the row and col
and will check if the row, col, and box are valid so we can place the number
in the position"""
# Check row
for i in range(len(board[pos[0]])):
if pos[0] != i and board[pos[0]][i] == num:
return False
# Check col
for i in range(len(board)):
if pos[1] != i and board[i][pos[1]] == num:
return False
pos_row = pos[0] // 3
pos_col = pos[1] // 3
for i in range(pos_row*3 ,pos_row*3 + 3):
for j in range(pos_col * 3, pos_col*3 + 3):
if (i,j) != pos and board[i][j] == num:
return False
return True
def solve(self):
"""Using backtracking algorithm to solve the solved_board variable"""
find = self.find_empty(self.solved_board)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if(self.is_valid(self.solved_board, i, (row, col))):
self.solved_board[row][col] = i
if self.solve():
return self.solved_board
self.solved_board[row][col] = 0
return False
sudoku = Sudoku(grid)
sudoku.print_original_board()
print(" ")
sudoku.solve()
sudoku.print_original_board() # <---- This prints the solved board
```
|
2021/05/06
|
[
"https://Stackoverflow.com/questions/67415482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7311644/"
] |
Yeah, `board[:]` does create a new list -- of all those old inner lists:
```py
In [23]: board = [[1], [2]]
In [24]: board2 = board[:]
In [25]: board2[0] is board[0]
Out[25]: True
In [26]: board2[0][0] += 10
In [28]: board
Out[28]: [[11], [2]]
```
You'd need to deepcopy it; e.g.,
```py
solved_board = [row[:] for row in board]
```
|
Try deepcopy method
```
from copy import deepcopy
def __init__(self, board):
self.board = board
self.solved_board = deepcopy(board)
```
|
67,415,482
|
I created a Sudoku class in python, I want to solve the board and also keep an instance variable with the original board, but when I use the `solve()` method which uses the recursive backtracking algorithm `self.board` changes together with `self.solved_board` why is that, and how can I keep a variable with the original copy?
```
grid = [ [3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0] ]
class Sudoku:
def __init__(self, board):
self.board = board
self.solved_board = board[:] #<--- I used the [:] because I thought this will create a new list
def get_board(self):
return self.board
def set_board(self, board):
self.board = board
self.solved_board = board
def print_original_board(self):
self.print(self.board)
def print_solved_board(self):
self.print(self.solved_board)
def print(self, board):
"""Receiving a matrix and printing a board with seperation"""
for i in range(len(board)):
if i % 3 == 0 and i!=0:
print('---------------------------------')
for j in range(len(board[i])):
if j%3==0 and j!=0:
print(" | ", end='')
print(" " + str(board[i][j]) + " ", end='')
print('')
def find_empty(self,board):
"""Receiving a matrix, loops through it, and return a tuple
with the row and the column of the free stop in the matrix"""
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==0:
return (i,j)
return None
def is_valid(self, board, num, pos):
"""Receiving matrix, a number we want to insert, and a tuple with the row and col
and will check if the row, col, and box are valid so we can place the number
in the position"""
# Check row
for i in range(len(board[pos[0]])):
if pos[0] != i and board[pos[0]][i] == num:
return False
# Check col
for i in range(len(board)):
if pos[1] != i and board[i][pos[1]] == num:
return False
pos_row = pos[0] // 3
pos_col = pos[1] // 3
for i in range(pos_row*3 ,pos_row*3 + 3):
for j in range(pos_col * 3, pos_col*3 + 3):
if (i,j) != pos and board[i][j] == num:
return False
return True
def solve(self):
"""Using backtracking algorithm to solve the solved_board variable"""
find = self.find_empty(self.solved_board)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if(self.is_valid(self.solved_board, i, (row, col))):
self.solved_board[row][col] = i
if self.solve():
return self.solved_board
self.solved_board[row][col] = 0
return False
sudoku = Sudoku(grid)
sudoku.print_original_board()
print(" ")
sudoku.solve()
sudoku.print_original_board() # <---- This prints the solved board
```
|
2021/05/06
|
[
"https://Stackoverflow.com/questions/67415482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7311644/"
] |
`self.solved_board = board[:]` does indeed create a new list, but it references the same inner lists as `board`. You need to go one level deeper:
```
self.solved_board = [row[:] for row in board]
```
|
Try deepcopy method
```
from copy import deepcopy
def __init__(self, board):
self.board = board
self.solved_board = deepcopy(board)
```
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in...
|
To complement on @Peter's answer, I might add that the ipython "executable" you run are simply python script that launch the ipython shell. So a solution that worked for me was to change the python version that runs that script:
```bash
$ cp ipython ipython3
$ nano ipython3
```
Here is what the script looks like:
```py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from IPython import start_ipython
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(start_ipython())
```
You can now replace this first line with your correct version of python, for example, you may wan to use python 3:
```bash
$ which python3
/usr/bin/python3
```
so you would simply replace `/usr/bin/python` by `/usr/bin/python3` in your newly created ipython3 file!
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in...
|
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 project_name
source project_name/bin/activate
pip install ipython
```
Then the ipython version should match the python passed into virtualenv with `--python`.
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I find the simplest way to specify which python version to use is to explicitly call the ipython script using that version. To do this, you may need to know the path to the ipython script, which you can find by running `which ipython`. Then simply run `python <path-to-ipython>` to start ipython.
|
To complement on @Peter's answer, I might add that the ipython "executable" you run are simply python script that launch the ipython shell. So a solution that worked for me was to change the python version that runs that script:
```bash
$ cp ipython ipython3
$ nano ipython3
```
Here is what the script looks like:
```py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from IPython import start_ipython
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(start_ipython())
```
You can now replace this first line with your correct version of python, for example, you may wan to use python 3:
```bash
$ which python3
/usr/bin/python3
```
so you would simply replace `/usr/bin/python` by `/usr/bin/python3` in your newly created ipython3 file!
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 project_name
source project_name/bin/activate
pip install ipython
```
Then the ipython version should match the python passed into virtualenv with `--python`.
|
You can just:
```
$ python2.4 setup.py install --prefix=$HOME/usr
$ python2.5 setup.py install --prefix=$HOME/usr
```
or
```
alias ip4 "python2.4 $HOME/usr/bin/ipython"
alias ip5 "python2.5 $HOME/usr/bin/ipython"
```
[fyi](https://github.com/ipython/ipython/wiki/Frequently-asked-questions#q-running-ipython-against-multiple-versions-of-python)
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I find the simplest way to specify which python version to use is to explicitly call the ipython script using that version. To do this, you may need to know the path to the ipython script, which you can find by running `which ipython`. Then simply run `python <path-to-ipython>` to start ipython.
|
You can just:
```
$ python2.4 setup.py install --prefix=$HOME/usr
$ python2.5 setup.py install --prefix=$HOME/usr
```
or
```
alias ip4 "python2.4 $HOME/usr/bin/ipython"
alias ip5 "python2.5 $HOME/usr/bin/ipython"
```
[fyi](https://github.com/ipython/ipython/wiki/Frequently-asked-questions#q-running-ipython-against-multiple-versions-of-python)
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 project_name
source project_name/bin/activate
pip install ipython
```
Then the ipython version should match the python passed into virtualenv with `--python`.
|
Actually you can run the ipython with the python version you like:
```
python2.7 ipython
python3 ipython
```
This is easiest solution for me and avoids virtual env setup for one-shot trials.
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in...
|
I find the simplest way to specify which python version to use is to explicitly call the ipython script using that version. To do this, you may need to know the path to the ipython script, which you can find by running `which ipython`. Then simply run `python <path-to-ipython>` to start ipython.
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 project_name
source project_name/bin/activate
pip install ipython
```
Then the ipython version should match the python passed into virtualenv with `--python`.
|
I find the simplest way to specify which python version to use is to explicitly call the ipython script using that version. To do this, you may need to know the path to the ipython script, which you can find by running `which ipython`. Then simply run `python <path-to-ipython>` to start ipython.
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).)
To get ipython2.5, I installed ipython from your virtualenv:
```
virtualenv --python=/usr/bin/python2.5 project_name
source project_name/bin/activate
pip install ipython
```
Then the ipython version should match the python passed into virtualenv with `--python`.
|
To complement on @Peter's answer, I might add that the ipython "executable" you run are simply python script that launch the ipython shell. So a solution that worked for me was to change the python version that runs that script:
```bash
$ cp ipython ipython3
$ nano ipython3
```
Here is what the script looks like:
```py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from IPython import start_ipython
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(start_ipython())
```
You can now replace this first line with your correct version of python, for example, you may wan to use python 3:
```bash
$ which python3
/usr/bin/python3
```
so you would simply replace `/usr/bin/python` by `/usr/bin/python3` in your newly created ipython3 file!
|
308,254
|
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was a ipython2.4 package but it is deprecated.
|
2008/11/21
|
[
"https://Stackoverflow.com/questions/308254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in...
|
You can just:
```
$ python2.4 setup.py install --prefix=$HOME/usr
$ python2.5 setup.py install --prefix=$HOME/usr
```
or
```
alias ip4 "python2.4 $HOME/usr/bin/ipython"
alias ip5 "python2.5 $HOME/usr/bin/ipython"
```
[fyi](https://github.com/ipython/ipython/wiki/Frequently-asked-questions#q-running-ipython-against-multiple-versions-of-python)
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
I was also getting this error on a fresh install of XAMPP.
For those not comfortable with the command line, there is another way.
Based on the advice above (thank you), I used my old standard "Easy Find" to locate the latest version of my.cnf. Upon opening the file in an editor I discovered that the socket file was pointing to:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
I updated Navicat's Advanced properties/ Use socket file to the path above and bingo.
Hope this helps someone.
|
If you have installed mysql through homebrew, simple `brew services restart mysql` may help.
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
First of all I suggest you to use homebrew to install any third part libraries or tools on your mac. Have a look to : [Link](https://brew.sh/)
Otherwise for your problem you can search where is the mysql socket on your mac and then symlink it to /tmp.
In your terminal try something like :
```
locate mysql | grep sock
```
You will get something like :
```
/the/path/to/mysql.sock
```
Then do :
```
ln -s /the/path/to/mysql.sock /tmp/mysql.sock
```
This should works.
Also you can edit your php.ini file to set the correct path for the mysql socket.
Hope this help.
|
I am going to throw in my two cents here because I had this problem too but my circumstances are abnormal for most. My system had a blended install of Zend Server CE and XAMPP. I am running Mac OS X. And I decided to remove Zend from my system because it was being a pain in my butt.
Upon removing Zend, since both were using the same DB and Zend had it my system went crazy. Uninstalling and reinstalling XAMPP didn't help. After a couple hours (which I just literally got done with) of troubleshooting I found that I needed to search my system for all copies my.cnf. The reason being is that mysql still kept trying to look for the Zend mysql path and it was failing.
So I used locate to find it. I had to initiate locate (since I had never used it before) so that it could build a DB of files on my system. Then I ran "locate my.cnf" and I found one in "/private/etc". So I just renamed the file to my.cnf.old and tried to launch MySQL again. Bam! It works now.
I will say this, I had to have a co-worker help me out because I was just spinning my wheels on this one. I really hope this helps someone out there. Thanks!
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
First of all I suggest you to use homebrew to install any third part libraries or tools on your mac. Have a look to : [Link](https://brew.sh/)
Otherwise for your problem you can search where is the mysql socket on your mac and then symlink it to /tmp.
In your terminal try something like :
```
locate mysql | grep sock
```
You will get something like :
```
/the/path/to/mysql.sock
```
Then do :
```
ln -s /the/path/to/mysql.sock /tmp/mysql.sock
```
This should works.
Also you can edit your php.ini file to set the correct path for the mysql socket.
Hope this help.
|
I was getting some similar error and ended up here. I am using OSX 10.9.5. This solved my problems (hope it helps someone).
1) sudo mkdir /var/mysql
2) sudo ln -s /private/tmp/mysql.sock /var/mysql/mysql.sock
More informations: <http://glidingphenomena.blogspot.com.br/2010/03/fixing-warning-mysqlconnect-cant.html>
Thanks!
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
I was getting some similar error and ended up here. I am using OSX 10.9.5. This solved my problems (hope it helps someone).
1) sudo mkdir /var/mysql
2) sudo ln -s /private/tmp/mysql.sock /var/mysql/mysql.sock
More informations: <http://glidingphenomena.blogspot.com.br/2010/03/fixing-warning-mysqlconnect-cant.html>
Thanks!
|
Ok, I just spent a couple hours struggling with this same problem. I had installed the dmg file for MySql 5.5.20 (64bit) for osx 10.6 on my iMac with OSX 10.7.2 - and the /tmp/mysql.sock was missing!
The answer turned out to be simply install the MySQLStartupItem.pkg that comes with the dmg file and restart the system. This starts up the daemons upon startup (which I hoped would be optional).
Magically, my /tmp/mysql.sock file appeared and all is well!
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
I was getting some similar error and ended up here. I am using OSX 10.9.5. This solved my problems (hope it helps someone).
1) sudo mkdir /var/mysql
2) sudo ln -s /private/tmp/mysql.sock /var/mysql/mysql.sock
More informations: <http://glidingphenomena.blogspot.com.br/2010/03/fixing-warning-mysqlconnect-cant.html>
Thanks!
|
Found the solution:
I had the same issue and I did a lot of searches but couldn't solve the issue until I looked at my MySql config file.
In my config file socket was in line 21 and the path was
"/Applications/AMPPS/var/mysql.sock"
In Ampps application click on MySql tab and then click on configuration button.
You can also find the config file in "/Applications/AMPPS/mysql/etc" folder
So simply I added
'unix\_socket' => '/Applications/AMPPS/var/mysql.sock',
to my database.php in mysql array and it's worked for me.
After host line. I have tested with localhost and 127.0.0.1 and both worked
Hopefully it's working for you too.
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
I am going to throw in my two cents here because I had this problem too but my circumstances are abnormal for most. My system had a blended install of Zend Server CE and XAMPP. I am running Mac OS X. And I decided to remove Zend from my system because it was being a pain in my butt.
Upon removing Zend, since both were using the same DB and Zend had it my system went crazy. Uninstalling and reinstalling XAMPP didn't help. After a couple hours (which I just literally got done with) of troubleshooting I found that I needed to search my system for all copies my.cnf. The reason being is that mysql still kept trying to look for the Zend mysql path and it was failing.
So I used locate to find it. I had to initiate locate (since I had never used it before) so that it could build a DB of files on my system. Then I ran "locate my.cnf" and I found one in "/private/etc". So I just renamed the file to my.cnf.old and tried to launch MySQL again. Bam! It works now.
I will say this, I had to have a co-worker help me out because I was just spinning my wheels on this one. I really hope this helps someone out there. Thanks!
|
Found the solution:
I had the same issue and I did a lot of searches but couldn't solve the issue until I looked at my MySql config file.
In my config file socket was in line 21 and the path was
"/Applications/AMPPS/var/mysql.sock"
In Ampps application click on MySql tab and then click on configuration button.
You can also find the config file in "/Applications/AMPPS/mysql/etc" folder
So simply I added
'unix\_socket' => '/Applications/AMPPS/var/mysql.sock',
to my database.php in mysql array and it's worked for me.
After host line. I have tested with localhost and 127.0.0.1 and both worked
Hopefully it's working for you too.
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
First of all I suggest you to use homebrew to install any third part libraries or tools on your mac. Have a look to : [Link](https://brew.sh/)
Otherwise for your problem you can search where is the mysql socket on your mac and then symlink it to /tmp.
In your terminal try something like :
```
locate mysql | grep sock
```
You will get something like :
```
/the/path/to/mysql.sock
```
Then do :
```
ln -s /the/path/to/mysql.sock /tmp/mysql.sock
```
This should works.
Also you can edit your php.ini file to set the correct path for the mysql socket.
Hope this help.
|
Ok, I just spent a couple hours struggling with this same problem. I had installed the dmg file for MySql 5.5.20 (64bit) for osx 10.6 on my iMac with OSX 10.7.2 - and the /tmp/mysql.sock was missing!
The answer turned out to be simply install the MySQLStartupItem.pkg that comes with the dmg file and restart the system. This starts up the daemons upon startup (which I hoped would be optional).
Magically, my /tmp/mysql.sock file appeared and all is well!
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
First of all I suggest you to use homebrew to install any third part libraries or tools on your mac. Have a look to : [Link](https://brew.sh/)
Otherwise for your problem you can search where is the mysql socket on your mac and then symlink it to /tmp.
In your terminal try something like :
```
locate mysql | grep sock
```
You will get something like :
```
/the/path/to/mysql.sock
```
Then do :
```
ln -s /the/path/to/mysql.sock /tmp/mysql.sock
```
This should works.
Also you can edit your php.ini file to set the correct path for the mysql socket.
Hope this help.
|
I was also getting this error on a fresh install of XAMPP.
For those not comfortable with the command line, there is another way.
Based on the advice above (thank you), I used my old standard "Easy Find" to locate the latest version of my.cnf. Upon opening the file in an editor I discovered that the socket file was pointing to:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
I updated Navicat's Advanced properties/ Use socket file to the path above and bingo.
Hope this helps someone.
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
Ok, I just spent a couple hours struggling with this same problem. I had installed the dmg file for MySql 5.5.20 (64bit) for osx 10.6 on my iMac with OSX 10.7.2 - and the /tmp/mysql.sock was missing!
The answer turned out to be simply install the MySQLStartupItem.pkg that comes with the dmg file and restart the system. This starts up the daemons upon startup (which I hoped would be optional).
Magically, my /tmp/mysql.sock file appeared and all is well!
|
If you have installed mysql through homebrew, simple `brew services restart mysql` may help.
|
5,784,791
|
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock that Sequel Pro was using: /tmp/mysql.sock.
But now I can't access the local server at all. As far as I can tell, there is no mysql.sock file anywhere on my computer, not in /tmp/ or anywhere else.
I can start the mysql server from Terminal, but it logs me out automatically after a minute:
```
110425 17:36:18 mysqld_safe Logging to '/usr/local/mysql/data/dn0a208bf7.sunet.err'.
110425 17:36:18 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
110425 17:37:58 mysqld_safe mysqld from pid file /usr/local/mysql/data/dn0a208bf7.sunet.pid ended
```
If I try to call "mysql" from the command line (which worked perfectly earlier today):
```
ERROR 2002 (HY000): Can\'t connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```
The PHP error is of course similar:
```
PHP Warning: mysql_real_escape_string(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock)
```
Also, there is no "my.cnf" file in my mysql installation directory: /usr/local/mysql. There are my.cnf files for the mysql installations that come along with XAMPP. Those also have the default socket listed as '/tmp/mysql.sock', but I had to change them manually.
Any ideas what's going on? Why would modifying the php.ini file have produced a change for Sequel Pro as well?
|
2011/04/26
|
[
"https://Stackoverflow.com/questions/5784791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321838/"
] |
I was getting some similar error and ended up here. I am using OSX 10.9.5. This solved my problems (hope it helps someone).
1) sudo mkdir /var/mysql
2) sudo ln -s /private/tmp/mysql.sock /var/mysql/mysql.sock
More informations: <http://glidingphenomena.blogspot.com.br/2010/03/fixing-warning-mysqlconnect-cant.html>
Thanks!
|
I was also getting this error on a fresh install of XAMPP.
For those not comfortable with the command line, there is another way.
Based on the advice above (thank you), I used my old standard "Easy Find" to locate the latest version of my.cnf. Upon opening the file in an editor I discovered that the socket file was pointing to:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
I updated Navicat's Advanced properties/ Use socket file to the path above and bingo.
Hope this helps someone.
|
61,261,306
|
I recently started exploring VS Code for developing Python code and I’m running into an issue when I try to import a module from a subfolder. The exact same code runs perfectly when I execute it in a Jupyter notebook (the subfolders contain the `__init__.py` files etc.) I believe I followed the instructions for setting up the VS Python extension correctly. Everything else except this one import command works well, but I haven’t been able to figure what exactly is going wrong.
The structure of the project is as follows: The root folder, which is set as the `cwd` contains two subfolders (`src` and `bld`). `src` contains the `py`-file that imports a module that is saved in `foo.py`in the `bld`-folder using `from bld.foo import foo_function`
When running the file, I get the following error: `ModuleNotFoundError: No module named ‘bld'`. I have several Anaconda Python environments installed and get the same problem with each of them. When copying `foo.py` to the `src` directory and using `from foo import foo_function` everything works.
My `launch.json` file is as follows:
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"cwd": "${workspaceFolder}",
"env": {"PYTHONPATH": "${workspaceFolder}:${workspaceFolder}/bld"},
"console": "integratedTerminal"
}
]
}
```
Any ideas or help would be greatly appreciated!
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61261306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952633/"
] |
Stefan‘s method worked for me.
Taking as example filesystem:
workspaceFolder/folder/subfolder1/subfolder2/bar.py
I wasn't able to import subfolders like:
`from folder.subfolder1.subfolder2 import bar`
It said: `ModuleNotFoundError: No module named 'folder'`
I added to .vscode/settings.json the following:
```
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}"
}
```
I also added at the beginning of my code:
```
import sys
#[... more imports ...]
sys.path.append(workspaceFolder)
# and then, the subfolder import:
from folder.subfolder1.subfolder2 import bar
```
Now, it works.
Note: all my folders and subfolders have an empty file named `__init__.py`. I still had to do the steps described above.
VSCode version: 1.52.0 (from 10-dec-2020)
|
I think I finally figured out the answer myself: The integrated terminal does not scan the `PYTHONPATH` from the `.env`-file. When running the file in an integrated window, the `PYTHONPATH` is correctly taken from `.env`, however. So in order to run my script in the terminal I had to add the `terminal.integrated.env.*` line in my `settings.json` as follows:
```
{
"python.pythonPath": "/anaconda3/envs/py36/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.flake8Enabled": false,
"python.envFile": "${workspaceFolder}/.env",
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}"
}
}
```
|
61,279,933
|
In python, I run this simple code:
```py
print('number is %.15f'%1.6)
```
which works fine (Output: `number is 1.600000000000000`), but when I take the decimal places to `16>=`, I start getting random numbers at the end. For example:
```py
print('number is %.16f'%1.6)
```
Output: `number is 1.6000000000000001` and
```py
print('number is %.20f'%1.6)
```
Output: `number is 1.60000000000000008882`
Does this have to do with the way computers compute numbers?
edit: Thanks for all the responses! I understand it now and it was fun to learn
|
2020/04/17
|
[
"https://Stackoverflow.com/questions/61279933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13159127/"
] |
Work-around
1. Open Hyper-V Manager under Windows Administrative Tools
2. Note DockerDesktopVM is not running under Virtual Machines
3. Under the Actions pane, click Stop Service, then click Start Service
4. Restart Docker Desktop
Its worked for me
|
Make sure that the VT-X virtualization is enabled in your BIOS
|
61,279,933
|
In python, I run this simple code:
```py
print('number is %.15f'%1.6)
```
which works fine (Output: `number is 1.600000000000000`), but when I take the decimal places to `16>=`, I start getting random numbers at the end. For example:
```py
print('number is %.16f'%1.6)
```
Output: `number is 1.6000000000000001` and
```py
print('number is %.20f'%1.6)
```
Output: `number is 1.60000000000000008882`
Does this have to do with the way computers compute numbers?
edit: Thanks for all the responses! I understand it now and it was fun to learn
|
2020/04/17
|
[
"https://Stackoverflow.com/questions/61279933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13159127/"
] |
I was facing the same issue I resolved this issue following below steps.
If you are able to run Windows container that means issue is with Hyper-V
1. Enable hyper on VM by -
[](https://i.stack.imgur.com/mlaQh.png)
2. We must enable hardware virtulization too this can be done by(IT team can help as this should be done on CPU level)
[](https://i.stack.imgur.com/Gl2sP.png)
|
Make sure that the VT-X virtualization is enabled in your BIOS
|
61,279,933
|
In python, I run this simple code:
```py
print('number is %.15f'%1.6)
```
which works fine (Output: `number is 1.600000000000000`), but when I take the decimal places to `16>=`, I start getting random numbers at the end. For example:
```py
print('number is %.16f'%1.6)
```
Output: `number is 1.6000000000000001` and
```py
print('number is %.20f'%1.6)
```
Output: `number is 1.60000000000000008882`
Does this have to do with the way computers compute numbers?
edit: Thanks for all the responses! I understand it now and it was fun to learn
|
2020/04/17
|
[
"https://Stackoverflow.com/questions/61279933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13159127/"
] |
Work-around
1. Open Hyper-V Manager under Windows Administrative Tools
2. Note DockerDesktopVM is not running under Virtual Machines
3. Under the Actions pane, click Stop Service, then click Start Service
4. Restart Docker Desktop
Its worked for me
|
I was facing the same issue I resolved this issue following below steps.
If you are able to run Windows container that means issue is with Hyper-V
1. Enable hyper on VM by -
[](https://i.stack.imgur.com/mlaQh.png)
2. We must enable hardware virtulization too this can be done by(IT team can help as this should be done on CPU level)
[](https://i.stack.imgur.com/Gl2sP.png)
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:
```py
#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl
def runMacro():
if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = wincl.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run\
("ThisWorkbook.Template2G")
#Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
1. File > Options > Trust Center
2. Click on Trust Center Settings... button
3. Macro Settings > Check Enable all macros
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
1. File > Options > Trust Center
2. Click on Trust Center Settings... button
3. Macro Settings > Check Enable all macros
|
For Python 3.7 or later,(2018-10-10), I have to combine both @Alejandro BR and SMNALLY's answer, coz @Alejandro forget to define wincl.
```
import os, os.path
import win32com.client
if os.path.exists('C:/Users/jz/Desktop/test.xlsm'):
excel_macro = win32com.client.DispatchEx("Excel.Application") # DispatchEx is required in the newest versions of Python.
excel_path = os.path.expanduser('C:/Users/jz/Desktop/test.xlsm')
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run("test.xlsm!Module1.Macro1") # update Module1 with your module, Macro1 with your macro
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
1. File > Options > Trust Center
2. Click on Trust Center Settings... button
3. Macro Settings > Check Enable all macros
|
A variation on SMNALLY's code that doesn't quit Excel if you already have it open:
```py
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
wb.Close(False) #close the work sheet object rather than quitting excel
del wb
del xl
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I would expect the error is to do with the macro you're calling, try the following bit of code:
### Code
```
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1)
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
xl.Application.Quit() # Comment this out if your excel script closes
del xl
```
|
Just a quick note with a xlsm with spaces.
```
file = 'file with spaces.xlsm'
excel_macro.Application.Run('\'' + file + '\'' + "!Module1.Macro1")
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I would expect the error is to do with the macro you're calling, try the following bit of code:
### Code
```
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1)
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
xl.Application.Quit() # Comment this out if your excel script closes
del xl
```
|
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com.
I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script.
Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
```
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
```
wait for Python to finish its work.
```
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:
```py
#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl
def runMacro():
if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = wincl.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run\
("ThisWorkbook.Template2G")
#Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
A variation on SMNALLY's code that doesn't quit Excel if you already have it open:
```py
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
wb.Close(False) #close the work sheet object rather than quitting excel
del wb
del xl
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:
```py
#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl
def runMacro():
if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = wincl.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run\
("ThisWorkbook.Template2G")
#Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
For Python 3.7 or later,(2018-10-10), I have to combine both @Alejandro BR and SMNALLY's answer, coz @Alejandro forget to define wincl.
```
import os, os.path
import win32com.client
if os.path.exists('C:/Users/jz/Desktop/test.xlsm'):
excel_macro = win32com.client.DispatchEx("Excel.Application") # DispatchEx is required in the newest versions of Python.
excel_path = os.path.expanduser('C:/Users/jz/Desktop/test.xlsm')
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run("test.xlsm!Module1.Macro1") # update Module1 with your module, Macro1 with your macro
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I would expect the error is to do with the macro you're calling, try the following bit of code:
### Code
```
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1)
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
xl.Application.Quit() # Comment this out if your excel script closes
del xl
```
|
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
1. File > Options > Trust Center
2. Click on Trust Center Settings... button
3. Macro Settings > Check Enable all macros
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:
```py
#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl
def runMacro():
if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = wincl.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run\
("ThisWorkbook.Template2G")
#Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
```
|
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com.
I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script.
Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
```
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
```
wait for Python to finish its work.
```
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
```
|
19,616,205
|
I'm trying to run a macro via python but I'm not sure how to get it working...
I've got the following code so far, but it's not working.
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
xl.Application.Run("macrohere")
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
I get the following traceback:
```
Traceback (most recent call last):
File "C:\test.py", line 4, in <module>
xl.Application.Run("macrohere")
File "<COMObject <unknown>>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'macrohere'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
```
### EDIT
```
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1)
try:
xl.Application.Run("test.xlsm!testmacro.testmacro")
# It does run like this... but we get the following error:
# Traceback (most recent call last):
# File "C:\test.py", line 7, in <module>
# xl.Workbooks(1).Close(SaveChanges=0)
# File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
# return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
# com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
except:
# Except isn't catching the above error... :(
xl.Workbooks(1).Close(SaveChanges=0)
xl.Application.Quit()
xl=0
```
|
2013/10/27
|
[
"https://Stackoverflow.com/questions/19616205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487602/"
] |
A variation on SMNALLY's code that doesn't quit Excel if you already have it open:
```py
import os, os.path
import win32com.client
if os.path.exists("excelsheet.xlsm"):
xl=win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
wb.Close(False) #close the work sheet object rather than quitting excel
del wb
del xl
```
|
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com.
I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script.
Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
```
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
```
wait for Python to finish its work.
```
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
```
|
73,111,056
|
I am fairly new at writing code and trying to teach myself python and pyspark based on searching the web for answers to my problems. I am trying to build a historical record set based on daily changes. I periodically have to bump the semantic version, but do not want to lose my already collected historical data. If the job can run incrementally then it performs the incremental transform like normal. Any and all help is appreciated.
```
SEMANTIC_VERSION = 1
# if job cannot run incrementally
# joins current snapshot data with already collected historical data
if cannot_not_run_incrementally:
@transform(
history=Output(historical_output),
backup=Input(historical_output_backup),
source=Input(order_input),
)
def my_compute_function(source, history, backup, ctx):
input_df = (
source.dataframe()
.withColumn('record_date', F.current_date())
)
old_df = backup.dataframe()
joined = old_df.unionByName(input_df)
joined = joined.distinct()
history.write_dataframe(joined)
# if job can run incrementally perform incremental transform normally
else:
@incremental(snapshot_inputs=['source'], semantic_version=SEMANTIC_VERSION)
@transform(
history=Output(historical_output),
backup=Output(historical_output_backup),
source=Input(order_input),
)
def my_compute_function(source, history, backup):
input_df = (
source.dataframe()
.withColumn('record_date', F.current_date())
)
history.write_dataframe(input_df.distinct()
.subtract(history.dataframe('previous', schema=input_df.schema)))
backup.set_mode("replace")
backup.write_dataframe(history.dataframe())
```
working code based on information from the selected answer and comments.
```
SEMANTIC_VERSION = 3
@incremental(snapshot_inputs=['source'], semantic_version=SEMANTIC_VERSION)
@transform(
history=Output(),
backup=Output(),
source=Input(),
)
def compute(ctx, history, backup, source):
# running incrementally
if ctx.is_incremental:
input_df = (
source.dataframe()
.withColumn('record_date', F.current_date())
)
history.write_dataframe(input_df.subtract(history.dataframe('previous', schema=input_df.schema)))
backup.set_mode("replace")
backup.write_dataframe(history.dataframe().distinct())
# not running incrementally
else:
input_df = (
source.dataframe()
.withColumn('record_date', F.current_date())
)
backup.set_mode('modify') # use replace if you want to start fresh
backup.write_dataframe(input_df)
history.set_mode('replace')
history.write_dataframe(backup.dataframe().distinct())
```
|
2022/07/25
|
[
"https://Stackoverflow.com/questions/73111056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19213719/"
] |
You use the 'IncrementalTransformContext' of the transform to determine whether it is running incrementally.
This can be seen in the code below.
```
@incremental()
@transform(
x=Output(),
y=Input(),
z=Input(),
)
def compute(ctx, x, y, z):
if ctx.is_incremental:
## Some Code
else:
## Other Code
```
More information on `IncrementalTransformContext` can be found here on your environment ({URL}/workspace/documentation/product/transforms/python-transforms-api-incrementaltransformcontext) or here (<https://www.palantir.com/docs/foundry/transforms-python/transforms-python-api-classes/#incrementaltransformcontext>)
|
In an incremental transform, there is a boolean flag property called 'is\_incremental' in the [incremental transform context object](https://www.palantir.com/docs/foundry/transforms-python/incremental-reference/#incrementaltransformcontext).
Therefore, I think you can do a single incremental transform definition and based on the value of the is\_incremental you do the operations you want, I would try something like this:
```
SEMANTIC_VERSION = 1
@incremental(snapshot_inputs=['source'], semantic_version=SEMANTIC_VERSION)
@transform(
history=Output(historical_output),
backup=Input(historical_output_backup),
source=Input(order_input),
)
def my_compute_function(source, history, backup, ctx):
input_df = (
source.dataframe()
.withColumn('record_date', F.current_date())
)
# if job cannot run incrementally
# joins current snapshot data with already collected historical data
if not ctx.is_incremental:
old_df = backup.dataframe()
joined = old_df.unionByName(input_df)
joined = joined.distinct()
history.write_dataframe(joined)
else: # if job can run incrementally perform incremental transform normally
history.write_dataframe(input_df.distinct()
.subtract(history.dataframe('previous', schema=input_df.schema)))
backup.set_mode("replace")
backup.write_dataframe(history.dataframe())
```
|
4,827,244
|
I'm trying to get an implementation of github flavored markdown working in python, with no luck... I don't have much in the way of regex skills.
Here's the ruby code from [github](https://github.com/github/github-flavored-markdown/blob/gh-pages/code.rb#L17):
```
# in very clear cases, let newlines become <br /> tags
text.gsub!(/(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+/m) do |x|
x.gsub(/^(.+)$/, "\\1 ")
end
```
And here's what I've come up with so far in python 2.5:
```
def newline_callback(matchobj):
return re.sub(r'^(.+)$','\1 ',matchobj.group(0))
text = re.sub(r'(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+', newline_callback, text)
```
There just doesn't seem to be any effect at all :-/
If anyone has a fully working implementation of [github flavored markdown](http://github.github.com/github-flavored-markdown/) in python, other than [this one](http://gregbrown.co.nz/code/githib-flavoured-markdown-python-implementation/) (doesn't seem to work for newlines), I'd love to hear about it. I'm really most concerned about the newlines.
These are the tests for the regex, from github's ruby code:
```
>>> gfm_pre_filter('apple\\npear\\norange\\n\\nruby\\npython\\nerlang')
'apple \\npear \\norange\\n\\nruby \\npython \\nerlang'
>>> gfm_pre_filter('test \\n\\n\\n something')
'test \\n\\n\\n something'
>>> gfm_pre_filter('# foo\\n# bar')
'# foo\\n# bar'
>>> gfm_pre_filter('* foo\\n* bar')
'* foo\\n* bar'
```
|
2011/01/28
|
[
"https://Stackoverflow.com/questions/4827244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73831/"
] |
That Ruby version has **multiline modifier** in the regex, so you need to do the same in python:
```
def newline_callback(matchobj):
return re.sub(re.compile(r'^(.+)$', re.M),r'\1 ',matchobj.group(0))
text = re.sub(re.compile(r'(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+', re.M), newline_callback, text)
```
So that code will (like the Ruby version) add two spaces after before newline, except if we have two newlines (paragraph).
Are those test string you gave correct? That file you linked has this, and it works with that fixed code:
```
"apple\npear\norange\n\nruby\npython\nerlang"
->
"apple \npear \norange\n\nruby \npython \nerlang"
```
|
```
return re.sub(r'^(.+)$',r'\1 ',matchobj.group(0))
^^^--------------------------- you forgot this.
```
|
3,115,448
|
this html is [here](https://mail.google.com/mail/?ui=2&ik=a0b1e46c9c&view=att&th=1296be43b8e3bbd9&attid=0.1&disp=inline&zw) :
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>
<div bgcolor="#48486c">
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" background="http://title.jpg" height="130">
<tr height="129">
<td width="719" height="129"></td>
<td width="1" height="129"></td>
</tr>
<tr height="1">
<td width="720" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" height="203">
<tr height="20">
<td width="719" height="20"></td>
<td width="1" height="20"></td>
</tr>
<tr height="69">
<td width="719" height="69" valign="top" align="left">
<table width="719" border="1" cellspacing="2" cellpadding="0">
<tr>
<td bgcolor="a5fdf8" width="390"><b>Stream Name</b></td>
<td bgcolor="a5fdf8" width="61"><b>Status</b></td>
<td bgcolor="a5fdf8" width="61"><b>Duration</b></td>
<td bgcolor="a5fdf8" width="185"><b>Start</b></td>
</tr>
<tr bgcolor="white">
<td width="390">c:\streams\ours\Sony_AVCHD_<WBR>Test_Discs_60Hz_00001.m2ts</td>
<td width="61"><font color="#D0D0D0">----</font></td>
<td width="61">00:00:02</td>
<td width="185">2010/06/15-15:06:17</td>
</tr>
</table>
</td>
<td width="1" height="69"></td>
</tr>
<tr height="113">
<td width="720" height="113" colspan="2" valign="top" align="left">
<table width="721" border="1" cellspacing="2" cellpadding="0">
<tr bgcolor="a5fdf8">
<td width="299"><b>Test Category</b></td>
<td width="61"><b>Error</b></td>
<td width="62"><b>Warning</b></td>
<td width="275"><b>Details</b></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac">All Tests (Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ETSI TR-101-290 Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ISO/IEC Transport Stream Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> System Data T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> Prog(1)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> VES(0xe0)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> H.264/AVC Conformance</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_Conf.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Sequence</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Picture</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Slice</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Macroblock</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Block</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> HRD Tests</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_HRD.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> HRD level</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Video T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> AES(0xfd)</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#808080"> Audio Level Tests</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Audio T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
</table>
</td>
</tr>
<tr height="1">
<td width="719" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
</div>
</body></html>
```
has any python lib to do this ?
thanks
|
2010/06/25
|
[
"https://Stackoverflow.com/questions/3115448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] |
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) gets you almost all the way there:
```
>>> import BeautifulSoup
>>> f = open('a.html')
>>> soup = BeautifulSoup.BeautifulSoup(f)
>>> f.close()
>>> g = open('a.xml', 'w')
>>> print >> g, soup.prettify()
>>> g.close()
```
This closes all tags properly. The only issue remaining is that the `doctype` remains `HTML` -- to change that into the doctype of your choice, you only need to change the first line, which is not hard, e.g., instead of printing the prettified text directly,
```
>>> lines = soup.prettify().splitlines()
>>> lines[0] = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
>>> print >> g, '\n'.join(lines)
```
|
lxml works well:
```
from lxml import html, etree
doc = html.fromstring(open('a.html').read())
out = open('a.xhtml', 'wb')
out.write(etree.tostring(doc))
```
|
3,115,448
|
this html is [here](https://mail.google.com/mail/?ui=2&ik=a0b1e46c9c&view=att&th=1296be43b8e3bbd9&attid=0.1&disp=inline&zw) :
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>
<div bgcolor="#48486c">
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" background="http://title.jpg" height="130">
<tr height="129">
<td width="719" height="129"></td>
<td width="1" height="129"></td>
</tr>
<tr height="1">
<td width="720" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" height="203">
<tr height="20">
<td width="719" height="20"></td>
<td width="1" height="20"></td>
</tr>
<tr height="69">
<td width="719" height="69" valign="top" align="left">
<table width="719" border="1" cellspacing="2" cellpadding="0">
<tr>
<td bgcolor="a5fdf8" width="390"><b>Stream Name</b></td>
<td bgcolor="a5fdf8" width="61"><b>Status</b></td>
<td bgcolor="a5fdf8" width="61"><b>Duration</b></td>
<td bgcolor="a5fdf8" width="185"><b>Start</b></td>
</tr>
<tr bgcolor="white">
<td width="390">c:\streams\ours\Sony_AVCHD_<WBR>Test_Discs_60Hz_00001.m2ts</td>
<td width="61"><font color="#D0D0D0">----</font></td>
<td width="61">00:00:02</td>
<td width="185">2010/06/15-15:06:17</td>
</tr>
</table>
</td>
<td width="1" height="69"></td>
</tr>
<tr height="113">
<td width="720" height="113" colspan="2" valign="top" align="left">
<table width="721" border="1" cellspacing="2" cellpadding="0">
<tr bgcolor="a5fdf8">
<td width="299"><b>Test Category</b></td>
<td width="61"><b>Error</b></td>
<td width="62"><b>Warning</b></td>
<td width="275"><b>Details</b></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac">All Tests (Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ETSI TR-101-290 Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ISO/IEC Transport Stream Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> System Data T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> Prog(1)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> VES(0xe0)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> H.264/AVC Conformance</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_Conf.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Sequence</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Picture</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Slice</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Macroblock</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Block</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> HRD Tests</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_HRD.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> HRD level</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Video T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> AES(0xfd)</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#808080"> Audio Level Tests</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Audio T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
</table>
</td>
</tr>
<tr height="1">
<td width="719" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
</div>
</body></html>
```
has any python lib to do this ?
thanks
|
2010/06/25
|
[
"https://Stackoverflow.com/questions/3115448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] |
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) gets you almost all the way there:
```
>>> import BeautifulSoup
>>> f = open('a.html')
>>> soup = BeautifulSoup.BeautifulSoup(f)
>>> f.close()
>>> g = open('a.xml', 'w')
>>> print >> g, soup.prettify()
>>> g.close()
```
This closes all tags properly. The only issue remaining is that the `doctype` remains `HTML` -- to change that into the doctype of your choice, you only need to change the first line, which is not hard, e.g., instead of printing the prettified text directly,
```
>>> lines = soup.prettify().splitlines()
>>> lines[0] = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
>>> print >> g, '\n'.join(lines)
```
|
To piggyback off @Alex Martelli, as of `Python 2.5`, there is an xml module that comes baked into the standard library:
<https://docs.python.org/3.6/library/xml.html>
You could strip all HTML tags off, then format into xml and use the baked in XML library instead of bringing in another dependency. This is only advisable if you trust the source of the XML as you would be susceptible to all the standard XML vulnerabilities.
|
3,115,448
|
this html is [here](https://mail.google.com/mail/?ui=2&ik=a0b1e46c9c&view=att&th=1296be43b8e3bbd9&attid=0.1&disp=inline&zw) :
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>
<div bgcolor="#48486c">
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" background="http://title.jpg" height="130">
<tr height="129">
<td width="719" height="129"></td>
<td width="1" height="129"></td>
</tr>
<tr height="1">
<td width="720" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center" height="203">
<tr height="20">
<td width="719" height="20"></td>
<td width="1" height="20"></td>
</tr>
<tr height="69">
<td width="719" height="69" valign="top" align="left">
<table width="719" border="1" cellspacing="2" cellpadding="0">
<tr>
<td bgcolor="a5fdf8" width="390"><b>Stream Name</b></td>
<td bgcolor="a5fdf8" width="61"><b>Status</b></td>
<td bgcolor="a5fdf8" width="61"><b>Duration</b></td>
<td bgcolor="a5fdf8" width="185"><b>Start</b></td>
</tr>
<tr bgcolor="white">
<td width="390">c:\streams\ours\Sony_AVCHD_<WBR>Test_Discs_60Hz_00001.m2ts</td>
<td width="61"><font color="#D0D0D0">----</font></td>
<td width="61">00:00:02</td>
<td width="185">2010/06/15-15:06:17</td>
</tr>
</table>
</td>
<td width="1" height="69"></td>
</tr>
<tr height="113">
<td width="720" height="113" colspan="2" valign="top" align="left">
<table width="721" border="1" cellspacing="2" cellpadding="0">
<tr bgcolor="a5fdf8">
<td width="299"><b>Test Category</b></td>
<td width="61"><b>Error</b></td>
<td width="62"><b>Warning</b></td>
<td width="275"><b>Details</b></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac">All Tests (Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ETSI TR-101-290 Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> ISO/IEC Transport Stream Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> System Data T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> Prog(1)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> VES(0xe0)</font></td>
<td width="61"><font color="#ff0000">34787</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> H.264/AVC Conformance</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_Conf.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Sequence</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Picture</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Slice</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Macroblock</font></td>
<td width="61"><font color="#ff0000">34718</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> Block</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#1010F0"> HRD Tests</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275">
<a><font color="#ff0000">Sony_AVCHD_Test_Discs_60Hz_<WBR>00001.m2ts_Prog(1)_PID(0x1011)<WBR>_H264_HRD.txt</font></a><br>
</td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#101010"> HRD level</font></td>
<td width="61"><font color="#ff0000">69</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Video T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#099eac"> AES(0xfd)</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="61"><font color="#000000">0</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#808080"> Audio Level Tests</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="61"><font color="#808080">Disabled</font></td>
<td width="275"></td>
</tr>
<tr bgcolor="white">
<td width="299"><font color="#800000"> Audio T-STD Tests</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="61"><font color="#800000">No Lic</font></td>
<td width="275"></td>
</tr>
</table>
</td>
</tr>
<tr height="1">
<td width="719" height="1"></td>
<td width="1" height="1"></td>
</tr>
</table>
</div>
</body></html>
```
has any python lib to do this ?
thanks
|
2010/06/25
|
[
"https://Stackoverflow.com/questions/3115448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] |
lxml works well:
```
from lxml import html, etree
doc = html.fromstring(open('a.html').read())
out = open('a.xhtml', 'wb')
out.write(etree.tostring(doc))
```
|
To piggyback off @Alex Martelli, as of `Python 2.5`, there is an xml module that comes baked into the standard library:
<https://docs.python.org/3.6/library/xml.html>
You could strip all HTML tags off, then format into xml and use the baked in XML library instead of bringing in another dependency. This is only advisable if you trust the source of the XML as you would be susceptible to all the standard XML vulnerabilities.
|
6,987,413
|
I started using the protocol buffer library, but noticed that it was using huge amounts of memory. pympler.asizeof shows that a single one of my objects is about 76k! Basically, it contains a few strings, some numbers, and some enums, and some optional lists of same. If I were writing the same thing as a C-struct, I would expect it to be under a few hundred bytes, and indeed the ByteSize method returns 121 (the size of the serialized string).
Is that you expect from the library? I had heard it was slow, but this is unusable and makes me more inclined to believe I'm misusing it.
**Edit**
Here is an example I constructed. This is a pb file similar, but simpler than what I've been using
```
package pb;
message A {
required double a = 1;
}
message B {
required double b = 1;
}
message C {
required double c = 1;
optional string s = 2;
}
message D {
required string d = 1;
optional string e = 2;
required A a = 3;
optional B b = 4;
repeated C c = 5;
}
```
And here I am using it
```
>>> import pb_pb2
>>> a = pb_pb2.D()
>>> a.d = "a"
>>> a.e = "e"
>>> a.a.a = 1
>>> a.b.b = 2
>>> c = a.c.add()
>>> c.c = 5
>>> c.s = "s"
>>> import pympler.asizeof
>>> pympler.asizeof.asizeof(a)
21440
>>> a.ByteSize()
42
```
I have version 2.2.0 of protobuf (a bit old at this point), and python 2.6.4.
|
2011/08/08
|
[
"https://Stackoverflow.com/questions/6987413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/189456/"
] |
Object instances have a bigger memory footprint in python than in compiled languages. For example, the following code, which creates very simple classes mimicking your proto displays 1440:
```
class A:
def __init__(self):
self.a = 0.0
class B:
def __init__(self):
self.b = 0.0
class C:
def __init__(self):
self.c = 0.0
self.s = ""
class D:
def __init__(self):
self.d = ""
self.e = ""
self.e_isset = 1
self.a = A()
self.b = B()
self.b_isset = 1
self.c = [C()]
d = D()
print asizeof(d)
```
I am not surprised that protobuf's generated classes take 20 times more memory, as they add a lot of boiler plate.
The C++ version surely doesn't suffer from this.
|
Edit: This isn't likely your actual issue here, but we've just been experiencing a 45MB protobuf message taking > 4GB ram when decoding. It appears to be this: <https://github.com/google/protobuf/issues/156>
which was known about in protobuf 2.6 and a fix was only merged onto master march 7 this year: <https://github.com/google/protobuf/commit/f6d8c833845b90f61b95234cd090ec6e70058d06>
|
69,495,394
|
input file.csv
```
['NE,PORT,EVENT,TIME,VALUE',
'NODE,13,MAX,2021-08-30 09:15:00+01:00 DST,-10.9',
'NODE,13,MIN,2021-08-30 09:15:00+01:00 DST,-11.0',
'NODE,13,CUR,2021-08-30 09:15:00+01:00 DST,-10.9',
'NODE,13,MAX,2021-08-30 10:30:00+01:00 DST,-12.9',
'NODE,13,MIN,2021-08-30 10:30:00+01:00 DST,-10.0',
'NODE,13,CUR,2021-08-30 10:30:00+01:00 DST,-12.9']
```
python code:
```
intext=open('file.csv', 'r')
check=intext.readlines()
for lista in check:
lista_split=lista.split(",")
lista_split.extend(['MAX','MIN','CUR'])
lista_index=[0,1,2,3,4]
lista_index.extend([5,6,7])
contents=list(lista_split[i] for i in lista_index)
if contents[2]==('MAX'):
contents[5] = contents[4])
elif contents[2]==('MIN'):
contents[6] = contents[4])
elif contents[2]==('CUR'):
contents[7] = contents[4])
contents.remove(contents[2])
contents.remove(contents[4])
print(contents)
```
step1 move EVENT as columns and the corresponding value, step2 clean columns (remove EVENT and VALUE), done!
```
['NE', 'PORT', 'TIME', 'MAX', 'MIN', 'CUR']
['NODE', '13', '2021-08-30 09:15:00+01:00 DST', '-10.9', 'MIN', 'CUR']
['NODE', '13', '2021-08-30 09:15:00+01:00 DST', 'MAX', '-11.0', 'CUR']
['NODE', '13', '2021-08-30 09:15:00+01:00 DST', 'MAX', 'MIN', '-10.9']
['NODE', '13', '2021-08-30 10:30:00+01:00 DST', '-12.9', 'MIN', 'CUR']
['NODE', '13', '2021-08-30 10:30:00+01:00 DST', 'MAX', '-10.0', 'CUR']
['NODE', '13', '2021-08-30 10:30:00+01:00 DST', 'MAX', 'MIN', '-12.9']
```
**target:**
```
['NE', 'PORT', 'TIME', 'MAX', 'MIN', 'CUR']
['NODE', '13', '2021-08-30 09:15:00+01:00 DST', '-10.9', '-11.0', '-10.9']
['NODE', '13', '2021-08-30 10:30:00+01:00 DST', '-12.9', '-10.0', '-12.9']
```
|
2021/10/08
|
[
"https://Stackoverflow.com/questions/69495394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17106118/"
] |
One way to do this is by creating a pivot table.
```
csv = ['NE,PORT,EVENT,TIME,VALUE',
'NODE,13,MAX,2021-08-30 09:15:00+01:00 DST,-10.9',
'NODE,13,MIN,2021-08-30 09:15:00+01:00 DST,-11.0',
'NODE,13,CUR,2021-08-30 09:15:00+01:00 DST,-10.9',
'NODE,13,MAX,2021-08-30 10:30:00+01:00 DST,-12.9',
'NODE,13,MIN,2021-08-30 10:30:00+01:00 DST,-10.0',
'NODE,13,CUR,2021-08-30 10:30:00+01:00 DST,-12.9']
csv = [x.split(",") for x in csv]
df = pd.DataFrame(csv[1:], columns=csv[0])
df["VALUE"] = df["VALUE"].astype(float)
df = df.pivot_table("VALUE", ["NE", "PORT", "TIME"], "EVENT")
df = df.reset_index().rename_axis(None, axis=1)
```
[result](https://i.stack.imgur.com/yWv6V.png)
|
i'll correct just your first step. your logic was good, but there was a lot of confusion due to too many lists
```
for lista in check:
lista=lista.split(",")
lista.extend(['MAX','MIN','CUR'])
if lista[2]==('MAX'):
lista[5] = lista[4]
elif lista[2]==('MIN'):
lista[6] = lista[4]
elif lista[2]==('CUR'):
lista[7] = lista[4]
lista.remove(lista[2])
lista.remove(lista[3]) #you removed an index before so it's not 4 anymore
print(lista)
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
Basically, it simplifies any loop that uses a boolean flag like this:
```
found = False # <-- initialize boolean
for divisor in range(2, n):
if n % divisor == 0:
found = True # <-- update boolean
break # optional, but continuing would be a waste of time
if found: # <-- check boolean
print n, "is composite"
else:
print n, "is prime"
```
and allows you to skip the management of the flag:
```
for divisor in range(2, n):
if n % divisor == 0:
print n, "is composite"
break
else:
print n, "is prime"
```
Note that there is already a natural place for code to execute when you do find a divisor - right before the `break`. The only new feature here is a place for code to execute when you tried all divisor and did not find any.
*This helps only in conjuction with `break`*. You still need booleans if you can't break (e.g. because you looking for the last match, or have to track several conditions in parallel).
Oh, and BTW, this works for while loops just as well.
any/all
-------
Nowdays, if the only purpose of the loop is a yes-or-no answer, you might be able to write it much shorter with the `any()`/`all()` functions with a generator or generator expression that yields booleans:
```
if any(n % divisor == 0
for divisor in range(2, n)):
print n, "is composite"
else:
print n, "is prime"
```
Note the elegancy! The code is 1:1 what you want to say!
[This is as effecient as a loop with a `break`, because the `any()` function is short-circuiting, only running the generator expression until it yeilds `True`. In fact it's usually even faster than a loop. Simpler Python code tends to have less overhear.]
This is less workable if you have other side effects - for example if you want to find the divisor. You can still do it (ab)using the fact that non-0 value are true in Python:
```
divisor = any(d for d in range(2, n) if n % d == 0)
if divisor:
print n, "is divisible by", divisor
else:
print n, "is prime"
```
but as you see this is getting shaky - wouldn't work if 0 was a possible divisor value...
|
Without using `break`, `else` blocks have no benefit for `for` and `while` statements. The following two examples are equivalent:
```
for x in range(10):
pass
else:
print "else"
for x in range(10):
pass
print "else"
```
The only reason for using `else` with `for` or `while` is to do something after the loop if it terminated normally, meaning without an explicit `break`.
After a lot of thinking, I can finally come up with a case where this might be useful:
```
def commit_changes(directory):
for file in directory:
if file_is_modified(file):
break
else:
# No changes
return False
# Something has been changed
send_directory_to_server()
return True
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
A use case of the `else` clause of loops is breaking out of nested loops:
```
while True:
for item in iterable:
if condition:
break
suite
else:
continue
break
```
It avoids repeating conditions:
```
while not condition:
for item in iterable:
if condition:
break
suite
```
|
Here you go:
```
a = ('y','a','y')
for x in a:
print x,
else:
print '!'
```
It's for the caboose.
edit:
```
# What happens if we add the ! to a list?
def side_effect(your_list):
your_list.extend('!')
for x in your_list:
print x,
claimant = ['A',' ','g','u','r','u']
side_effect(claimant)
print claimant[-1]
# oh no, claimant now ends with a '!'
```
edit:
```
a = (("this","is"),("a","contrived","example"),("of","the","caboose","idiom"))
for b in a:
for c in b:
print c,
if "is" == c:
break
else:
print
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
What could be more pythonic than PyPy?
Look at what I discovered starting at line 284 in ctypes\_configure/configure.py:
```
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
```
And here, from line 425 in pypy/annotation/annrpython.py ([clicky](http://codespeak.net/pypy/dist/pypy/annotation/annrpython.py))
```
if cell.is_constant():
return Constant(cell.const)
else:
for v in known_variables:
if self.bindings[v] is cell:
return v
else:
raise CannotSimplify
```
In pypy/annotation/binaryop.py, starting at line 751:
```
def is_((pbc1, pbc2)):
thistype = pairtype(SomePBC, SomePBC)
s = super(thistype, pair(pbc1, pbc2)).is_()
if not s.is_constant():
if not pbc1.can_be_None or not pbc2.can_be_None:
for desc in pbc1.descriptions:
if desc in pbc2.descriptions:
break
else:
s.const = False # no common desc in the two sets
return s
```
A non-one-liner in pypy/annotation/classdef.py, starting at line 176:
```
def add_source_for_attribute(self, attr, source):
"""Adds information about a constant source for an attribute.
"""
for cdef in self.getmro():
if attr in cdef.attrs:
# the Attribute() exists already for this class (or a parent)
attrdef = cdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
# we should reflow from all the reader's position,
# but as an optimization we try to see if the attribute
# has really been generalized
if attrdef.s_value != s_prev_value:
attrdef.mutated(cdef) # reflow from all read positions
return
else:
# remember the source in self.attr_sources
sources = self.attr_sources.setdefault(attr, [])
sources.append(source)
# register the source in any Attribute found in subclasses,
# to restore invariant (III)
# NB. add_constant_source() may discover new subdefs but the
# right thing will happen to them because self.attr_sources
# was already updated
if not source.instance_level:
for subdef in self.getallsubdefs():
if attr in subdef.attrs:
attrdef = subdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
if attrdef.s_value != s_prev_value:
attrdef.mutated(subdef) # reflow from all read positions
```
Later in the same file, starting at line 307, an example with an illuminating comment:
```
def generalize_attr(self, attr, s_value=None):
# if the attribute exists in a superclass, generalize there,
# as imposed by invariant (I)
for clsdef in self.getmro():
if attr in clsdef.attrs:
clsdef._generalize_attr(attr, s_value)
break
else:
self._generalize_attr(attr, s_value)
```
|
Without using `break`, `else` blocks have no benefit for `for` and `while` statements. The following two examples are equivalent:
```
for x in range(10):
pass
else:
print "else"
for x in range(10):
pass
print "else"
```
The only reason for using `else` with `for` or `while` is to do something after the loop if it terminated normally, meaning without an explicit `break`.
After a lot of thinking, I can finally come up with a case where this might be useful:
```
def commit_changes(directory):
for file in directory:
if file_is_modified(file):
break
else:
# No changes
return False
# Something has been changed
send_directory_to_server()
return True
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
What could be more pythonic than PyPy?
Look at what I discovered starting at line 284 in ctypes\_configure/configure.py:
```
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
```
And here, from line 425 in pypy/annotation/annrpython.py ([clicky](http://codespeak.net/pypy/dist/pypy/annotation/annrpython.py))
```
if cell.is_constant():
return Constant(cell.const)
else:
for v in known_variables:
if self.bindings[v] is cell:
return v
else:
raise CannotSimplify
```
In pypy/annotation/binaryop.py, starting at line 751:
```
def is_((pbc1, pbc2)):
thistype = pairtype(SomePBC, SomePBC)
s = super(thistype, pair(pbc1, pbc2)).is_()
if not s.is_constant():
if not pbc1.can_be_None or not pbc2.can_be_None:
for desc in pbc1.descriptions:
if desc in pbc2.descriptions:
break
else:
s.const = False # no common desc in the two sets
return s
```
A non-one-liner in pypy/annotation/classdef.py, starting at line 176:
```
def add_source_for_attribute(self, attr, source):
"""Adds information about a constant source for an attribute.
"""
for cdef in self.getmro():
if attr in cdef.attrs:
# the Attribute() exists already for this class (or a parent)
attrdef = cdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
# we should reflow from all the reader's position,
# but as an optimization we try to see if the attribute
# has really been generalized
if attrdef.s_value != s_prev_value:
attrdef.mutated(cdef) # reflow from all read positions
return
else:
# remember the source in self.attr_sources
sources = self.attr_sources.setdefault(attr, [])
sources.append(source)
# register the source in any Attribute found in subclasses,
# to restore invariant (III)
# NB. add_constant_source() may discover new subdefs but the
# right thing will happen to them because self.attr_sources
# was already updated
if not source.instance_level:
for subdef in self.getallsubdefs():
if attr in subdef.attrs:
attrdef = subdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
if attrdef.s_value != s_prev_value:
attrdef.mutated(subdef) # reflow from all read positions
```
Later in the same file, starting at line 307, an example with an illuminating comment:
```
def generalize_attr(self, attr, s_value=None):
# if the attribute exists in a superclass, generalize there,
# as imposed by invariant (I)
for clsdef in self.getmro():
if attr in clsdef.attrs:
clsdef._generalize_attr(attr, s_value)
break
else:
self._generalize_attr(attr, s_value)
```
|
Here you go:
```
a = ('y','a','y')
for x in a:
print x,
else:
print '!'
```
It's for the caboose.
edit:
```
# What happens if we add the ! to a list?
def side_effect(your_list):
your_list.extend('!')
for x in your_list:
print x,
claimant = ['A',' ','g','u','r','u']
side_effect(claimant)
print claimant[-1]
# oh no, claimant now ends with a '!'
```
edit:
```
a = (("this","is"),("a","contrived","example"),("of","the","caboose","idiom"))
for b in a:
for c in b:
print c,
if "is" == c:
break
else:
print
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
If you have a for loop you don't really have any condition statement. So break is your choice if you like to abort and then else can serve perfectly to handle the case where you were not happy.
```
for fruit in basket:
if fruit.kind in ['Orange', 'Apple']:
fruit.eat()
break
else:
print 'The basket contains no desirable fruit'
```
|
I was introduced to a wonderful idiom in which you can use a `for`/`break`/`else` scheme with an iterator to save both time and LOC. The example at hand was searching for the candidate for an incompletely qualified path. If you care to see the original context, please see [the original question](https://stackoverflow.com/a/18988504/691859).
```
def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
for pathitem in path:
for item in actual:
if pathitem == item:
break
else:
return False
return True
```
What makes the use of `for`/`else` so great here is the elegance of avoiding juggling a confusing boolean around. Without `else`, but hoping to achieve the same amount of short-circuiting, it might be written like so:
```
def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
failed = True
for pathitem in path:
failed = True
for item in actual:
if pathitem == item:
failed = False
break
if failed:
break
return not failed
```
I think the use of `else` makes it more elegant and more obvious.
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
If you have a for loop you don't really have any condition statement. So break is your choice if you like to abort and then else can serve perfectly to handle the case where you were not happy.
```
for fruit in basket:
if fruit.kind in ['Orange', 'Apple']:
fruit.eat()
break
else:
print 'The basket contains no desirable fruit'
```
|
Here you go:
```
a = ('y','a','y')
for x in a:
print x,
else:
print '!'
```
It's for the caboose.
edit:
```
# What happens if we add the ! to a list?
def side_effect(your_list):
your_list.extend('!')
for x in your_list:
print x,
claimant = ['A',' ','g','u','r','u']
side_effect(claimant)
print claimant[-1]
# oh no, claimant now ends with a '!'
```
edit:
```
a = (("this","is"),("a","contrived","example"),("of","the","caboose","idiom"))
for b in a:
for c in b:
print c,
if "is" == c:
break
else:
print
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
I was introduced to a wonderful idiom in which you can use a `for`/`break`/`else` scheme with an iterator to save both time and LOC. The example at hand was searching for the candidate for an incompletely qualified path. If you care to see the original context, please see [the original question](https://stackoverflow.com/a/18988504/691859).
```
def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
for pathitem in path:
for item in actual:
if pathitem == item:
break
else:
return False
return True
```
What makes the use of `for`/`else` so great here is the elegance of avoiding juggling a confusing boolean around. Without `else`, but hoping to achieve the same amount of short-circuiting, it might be written like so:
```
def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
failed = True
for pathitem in path:
failed = True
for item in actual:
if pathitem == item:
failed = False
break
if failed:
break
return not failed
```
I think the use of `else` makes it more elegant and more obvious.
|
A use case of the `else` clause of loops is breaking out of nested loops:
```
while True:
for item in iterable:
if condition:
break
suite
else:
continue
break
```
It avoids repeating conditions:
```
while not condition:
for item in iterable:
if condition:
break
suite
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
What could be more pythonic than PyPy?
Look at what I discovered starting at line 284 in ctypes\_configure/configure.py:
```
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
```
And here, from line 425 in pypy/annotation/annrpython.py ([clicky](http://codespeak.net/pypy/dist/pypy/annotation/annrpython.py))
```
if cell.is_constant():
return Constant(cell.const)
else:
for v in known_variables:
if self.bindings[v] is cell:
return v
else:
raise CannotSimplify
```
In pypy/annotation/binaryop.py, starting at line 751:
```
def is_((pbc1, pbc2)):
thistype = pairtype(SomePBC, SomePBC)
s = super(thistype, pair(pbc1, pbc2)).is_()
if not s.is_constant():
if not pbc1.can_be_None or not pbc2.can_be_None:
for desc in pbc1.descriptions:
if desc in pbc2.descriptions:
break
else:
s.const = False # no common desc in the two sets
return s
```
A non-one-liner in pypy/annotation/classdef.py, starting at line 176:
```
def add_source_for_attribute(self, attr, source):
"""Adds information about a constant source for an attribute.
"""
for cdef in self.getmro():
if attr in cdef.attrs:
# the Attribute() exists already for this class (or a parent)
attrdef = cdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
# we should reflow from all the reader's position,
# but as an optimization we try to see if the attribute
# has really been generalized
if attrdef.s_value != s_prev_value:
attrdef.mutated(cdef) # reflow from all read positions
return
else:
# remember the source in self.attr_sources
sources = self.attr_sources.setdefault(attr, [])
sources.append(source)
# register the source in any Attribute found in subclasses,
# to restore invariant (III)
# NB. add_constant_source() may discover new subdefs but the
# right thing will happen to them because self.attr_sources
# was already updated
if not source.instance_level:
for subdef in self.getallsubdefs():
if attr in subdef.attrs:
attrdef = subdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
if attrdef.s_value != s_prev_value:
attrdef.mutated(subdef) # reflow from all read positions
```
Later in the same file, starting at line 307, an example with an illuminating comment:
```
def generalize_attr(self, attr, s_value=None):
# if the attribute exists in a superclass, generalize there,
# as imposed by invariant (I)
for clsdef in self.getmro():
if attr in clsdef.attrs:
clsdef._generalize_attr(attr, s_value)
break
else:
self._generalize_attr(attr, s_value)
```
|
Perhaps the best answer comes from the official Python tutorial:
[break and continue Statements, and else Clauses on Loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops):
>
> *Loop statements may have an else
> clause; it is executed when the loop
> terminates through exhaustion of the
> list (with for) or when the condition
> becomes false (with while), but not
> when the loop is terminated by a break
> statement*
>
>
>
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
Perhaps the best answer comes from the official Python tutorial:
[break and continue Statements, and else Clauses on Loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops):
>
> *Loop statements may have an else
> clause; it is executed when the loop
> terminates through exhaustion of the
> list (with for) or when the condition
> becomes false (with while), but not
> when the loop is terminated by a break
> statement*
>
>
>
|
A use case of the `else` clause of loops is breaking out of nested loops:
```
while True:
for item in iterable:
if condition:
break
suite
else:
continue
break
```
It avoids repeating conditions:
```
while not condition:
for item in iterable:
if condition:
break
suite
```
|
685,758
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
2009/03/26
|
[
"https://Stackoverflow.com/questions/685758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55562/"
] |
If you have a for loop you don't really have any condition statement. So break is your choice if you like to abort and then else can serve perfectly to handle the case where you were not happy.
```
for fruit in basket:
if fruit.kind in ['Orange', 'Apple']:
fruit.eat()
break
else:
print 'The basket contains no desirable fruit'
```
|
Perhaps the best answer comes from the official Python tutorial:
[break and continue Statements, and else Clauses on Loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops):
>
> *Loop statements may have an else
> clause; it is executed when the loop
> terminates through exhaustion of the
> list (with for) or when the condition
> becomes false (with while), but not
> when the loop is terminated by a break
> statement*
>
>
>
|
32,043,990
|
I'm trying to get the `SPF records` of a `domains` and the domains are read from a file.When i am trying to get the spf contents and write it to a file and the code gives me the results of last domain got from input file.
```
Example `Input_Domains.txt`
blah.com
box.com
marketo.com
```
The output,I get is only for the `marketo.com`
```
#!/usr/bin/python
import sys
import socket
import dns.resolver
import re
def getspf (domain):
answers = dns.resolver.query(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith('v=spf1'):
return txt_string.replace('v=spf1','')
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
my_file=open("out_spf.txt","w")
my_file.write(full_spf)
my_file.close()
```
How can i solve this by writing all the spf contents of domains which i got it to file,Any suggestions please ?
|
2015/08/17
|
[
"https://Stackoverflow.com/questions/32043990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5093018/"
] |
It is because you are rewriting `full_spf` all the time so only last value is stored
```
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
```
**Modification:**
```
with open('Input_Domains.txt','r') as f:
full_spf=""
for line in f:
full_spf+=getspf(line.strip())+"\n"
```
|
Try using [a generator expression](https://wiki.python.org/moin/Generators) inside your `with` block, instead of a regular `for` loop:
```
full_spf = '\n'.join(getspf(line.strip()) for line in f)
```
This will grab all the lines at once, do your custom `getspf` operations to them, and then join them with newlines between.
The advantage to doing it this way is that conceptually you're doing a single transformation over the data. There's nothing inherently "loopy" about taking a block of data and processing it line-by-line, since it could be done in any order, all lines are independent. By doing it with a generator expression you are expressing your algorithm as a single transformation-and-assignment operation.
Edit: Small oversight, since `join` needs a list of strings, you'll have to return at least an empty string in every case from your `getspf` function, rather than defaulting to `None` when you don't return anything.
|
25,927,804
|
Hey guys For my school project I need to web scrape slideshare.net for page views using python. However, it wont let me scrape the page views of the user name (which the professor specifically told us to scrape) for example if I go to slideshare.net/Username on the bottom there will be a page view counter when i go into page source the code is
```
<span class="noWrap"> xxxx views </span>
```
when I plug this into python as
```
<span class="noWrap"> (.+?) </span>
```
Nothing happens all I get is [] in the out put window
HERE IS FULL CODE -
===================
```
import urllib
import re
symbolfile = open("viewpage.txt")
symbolslist = symbolfile.read()
for symbol in symbolslist:
print symbol
htmlfile = urllib.urlopen("http://www.slideshare.net/xxxxxxx")
htmltext = htmlfile.read()
regex = ' <span class="noWrap">(.+?)</span>'
regex_a = '<title>(.+?)</title>'
pattern = re.compile(regex)
pattern_a = re.compile(regex_a)
view = re.findall(pattern,htmltext)
view_a = re.findall(pattern_a,htmltext)
print (view, view_a)
```
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25927804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057203/"
] |
You have a space at the start of your regex string, so it will only match if there's (at least) one space before the `<span`...
So instead of
`regex = ' <span class="noWrap">(.+?)</span>'`
try
`regex = '<span class="noWrap">(.+?)</span>'`
or even better
`regex = r'<span class="noWrap">\s*(.+?)\s*</span>'`
Raw strings like `r'stuff'` are preferred for regex use, so you don't have to escape too much stuff inside the regex string.
The `\s` patterns will consume spaces so your won't need to use `strip()` on the data you capture with `findall()`.
I should also mention that `pattern.findall(text)` is a bit nicer syntax than `re.findall(pattern, text)`.
|
Although this in not an technically an answer you will need to change your regular expression. I suggest you look at the python regex chapters.
What I will tell you is that your line
```
regex = ' <span class="noWrap">(.+?)</span>'
```
will not match what you are after based on the output of the webpage since there are carriage returns in the html and your regex will not match these, hence the empty list when you run your script.
Or you could remove the carriage returns before you run your regex with
```
htmltext = htmltext.replace("\n","")
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Create an instance of `customLogger` in your log module and use it as a singleton - just use the imported instance, rather than the class.
|
You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the `logger = logging.getLogger(loggerName)` part):
```
def getLogger(name, logdir=LOGDIR_DEFAULT, level=logging.DEBUG, logformat=FORMAT):
base = os.path.basename(__file__)
loggerName = "%s.%s" % (base, name)
logFileName = os.path.join(logdir, "%s.log" % loggerName)
logger = logging.getLogger(loggerName)
logger.setLevel(level)
i = 0
while os.path.exists(logFileName) and not os.access(logFileName, os.R_OK | os.W_OK):
i += 1
logFileName = "%s.%s.log" % (logFileName.replace(".log", ""), str(i).zfill((len(str(i)) + 1)))
try:
#fh = logging.FileHandler(logFileName)
fh = RotatingFileHandler(filename=logFileName, mode="a", maxBytes=1310720, backupCount=50)
except IOError, exc:
errOut = "Unable to create/open log file \"%s\"." % logFileName
if exc.errno is 13: # Permission denied exception
errOut = "ERROR ** Permission Denied ** - %s" % errOut
elif exc.errno is 2: # No such directory
errOut = "ERROR ** No such directory \"%s\"** - %s" % (os.path.split(logFileName)[0], errOut)
elif exc.errno is 24: # Too many open files
errOut = "ERROR ** Too many open files ** - Check open file descriptors in /proc/<PID>/fd/ (PID: %s)" % os.getpid()
else:
errOut = "Unhandled Exception ** %s ** - %s" % (str(exc), errOut)
raise LogException(errOut)
else:
formatter = logging.Formatter(logformat)
fh.setLevel(level)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
class MainThread:
def __init__(self, cfgdefaults, configdir, pidfile, logdir, test=False):
self.logdir = logdir
logLevel = logging.DEBUG
logPrefix = "MainThread_TEST" if self.test else "MainThread"
try:
self.logger = getLogger(logPrefix, self.logdir, logLevel, FORMAT)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
os._exit(0)
else:
self.logger.debug("-------------------- MainThread created. Starting __init__() --------------------")
def run(self):
self.logger.debug("Initializing ReportThreads..")
for (group, cfg) in self.config.items():
self.logger.debug(" ------------------------------ GROUP '%s' CONFIG ------------------------------ " % group)
for k2, v2 in cfg.items():
self.logger.debug("%s <==> %s: %s" % (group, k2, v2))
try:
rt = ReportThread(self, group, cfg, self.logdir, self.test)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
self.logger.exception("Exception when creating ReportThread (%s)" % group)
logging.shutdown()
os._exit(1)
else:
self.threads.append(rt)
self.logger.debug("Threads initialized.. \"%s\"" % ", ".join([t.name for t in self.threads]))
for t in self.threads:
t.Start()
if not self.test:
self.loop()
class ReportThread:
def __init__(self, mainThread, name, config, logdir, test):
self.mainThread = mainThread
self.name = name
logLevel = logging.DEBUG
self.logger = getLogger("MainThread%s.ReportThread_%s" % ("_TEST" if self.test else "", self.name), logdir, logLevel, FORMAT)
self.logger.info("init database...")
self.initDB()
# etc....
if __name__ == "__main__":
# .....
MainThread(cfgdefaults=options.cfgdefaults, configdir=options.configdir, pidfile=options.pidfile, logdir=options.logdir, test=options.test)
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Use [`logging.getLogger(name)`](https://docs.python.org/3/library/logging.html#logging.getLogger) to create a named global logger.
**main.py**
```
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')
import submodule
```
**log.py**
```
import logging
def setup_custom_logger(name):
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger
```
**submodule.py**
```
import logging
logger = logging.getLogger('root')
logger.debug('submodule message')
```
**Output**
```
2011-10-01 20:08:40,049 - DEBUG - main - main message
2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message
```
|
Create an instance of `customLogger` in your log module and use it as a singleton - just use the imported instance, rather than the class.
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Since I haven't found a satisfactory answer, I would like to elaborate on the answer to the question a little bit in order to give some insight into the workings and intents of the `logging` library, that comes with Python's standard library.
In contrast to the approach of the OP (original poster) the library clearly separates the interface to the logger and configuration of the logger itself.
>
> The configuration of handlers is the prerogative of the application developer who uses your library.
>
>
>
That means you should *not* create a custom logger class and configure the logger inside that class by adding any configuration or whatsoever.
The `logging` library introduces four components: *loggers*, *handlers*, *filters*, and *formatters*.
>
> * Loggers expose the interface that application code directly uses.
> * Handlers send the log records (created by loggers) to the appropriate destination.
> * Filters provide a finer grained facility for determining which log records to output.
> * Formatters specify the layout of log records in the final output.
>
>
>
A common project structure looks like this:
```
Project/
|-- .../
| |-- ...
|
|-- project/
| |-- package/
| | |-- __init__.py
| | |-- module.py
| |
| |-- __init__.py
| |-- project.py
|
|-- ...
|-- ...
```
Inside your code (like in **module.py**) you refer to the logger instance of your module to log the events at their specific levels.
>
> A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
>
>
>
```
logger = logging.getLogger(__name__)
```
The special variable `__name__` refers to your module's name and looks something like `project.package.module` depending on your application's code structure.
**module.py** (and any other class) could essentially look like this:
```
import logging
...
log = logging.getLogger(__name__)
class ModuleClass:
def do_something(self):
log.debug('do_something() has been called!')
```
The logger in each module will propagate any event to the parent logger which in return passes the information to its attached *handler*! Analogously to the python package/module structure, the parent logger is determined by the namespace using "dotted module names". That's why it makes sense to initialize the logger with the special `__name__` variable (in the example above **name** matches the string *"project.package.module"*).
There are two options to configure the logger globally:
* Instantiate a logger in **project.py** with the name `__package__` which equals *"project"* in this example and is therefore the parent logger of the loggers of all submodules. It is only necessary to add an appropriate handler and formatter to *this* logger.
* Set up a logger with a handler and formatter in the executing script (like **main.py**) with the name of the topmost package.
>
> When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used.
>
>
>
The executing script, like **main.py** for example, might finally look something like this:
```
import logging
from project import App
def setup_logger():
# create logger
logger = logging.getLogger('project')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
if __name__ == '__main__' and __package__ is None:
setup_logger()
app = App()
app.do_some_funny_stuff()
```
The method call `log.setLevel(...)` specifies the lowest-severity log message a logger will *handle* but not necessarily output! It simply means the message is passed to the handler as long as the message's severity level is higher than (or equal to) the one that is set. But the *handler* is responsible for *handling* the log message (by printing or storing it for example).
Hence the `logging` library offers a structured and modular approach which just needs to be exploited according to one's needs.
[Logging documentation](https://docs.python.org/2/howto/logging.html)
|
Create an instance of `customLogger` in your log module and use it as a singleton - just use the imported instance, rather than the class.
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Create an instance of `customLogger` in your log module and use it as a singleton - just use the imported instance, rather than the class.
|
The python logging module is already good enough as global logger, you might simply looking for this:
**main.py**
```
import logging
logging.basicConfig(level = logging.DEBUG,format = '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
```
Put the codes above into your executing script, then you can use this logger with the same configs anywhere in your projects:
**module.py**
```
import logging
logger = logging.getLogger(__name__)
logger.info('hello world!')
```
For more complicated configs you may use a config file **logging.conf** with logging
```
logging.config.fileConfig("logging.conf")
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Use [`logging.getLogger(name)`](https://docs.python.org/3/library/logging.html#logging.getLogger) to create a named global logger.
**main.py**
```
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')
import submodule
```
**log.py**
```
import logging
def setup_custom_logger(name):
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger
```
**submodule.py**
```
import logging
logger = logging.getLogger('root')
logger.debug('submodule message')
```
**Output**
```
2011-10-01 20:08:40,049 - DEBUG - main - main message
2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message
```
|
You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the `logger = logging.getLogger(loggerName)` part):
```
def getLogger(name, logdir=LOGDIR_DEFAULT, level=logging.DEBUG, logformat=FORMAT):
base = os.path.basename(__file__)
loggerName = "%s.%s" % (base, name)
logFileName = os.path.join(logdir, "%s.log" % loggerName)
logger = logging.getLogger(loggerName)
logger.setLevel(level)
i = 0
while os.path.exists(logFileName) and not os.access(logFileName, os.R_OK | os.W_OK):
i += 1
logFileName = "%s.%s.log" % (logFileName.replace(".log", ""), str(i).zfill((len(str(i)) + 1)))
try:
#fh = logging.FileHandler(logFileName)
fh = RotatingFileHandler(filename=logFileName, mode="a", maxBytes=1310720, backupCount=50)
except IOError, exc:
errOut = "Unable to create/open log file \"%s\"." % logFileName
if exc.errno is 13: # Permission denied exception
errOut = "ERROR ** Permission Denied ** - %s" % errOut
elif exc.errno is 2: # No such directory
errOut = "ERROR ** No such directory \"%s\"** - %s" % (os.path.split(logFileName)[0], errOut)
elif exc.errno is 24: # Too many open files
errOut = "ERROR ** Too many open files ** - Check open file descriptors in /proc/<PID>/fd/ (PID: %s)" % os.getpid()
else:
errOut = "Unhandled Exception ** %s ** - %s" % (str(exc), errOut)
raise LogException(errOut)
else:
formatter = logging.Formatter(logformat)
fh.setLevel(level)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
class MainThread:
def __init__(self, cfgdefaults, configdir, pidfile, logdir, test=False):
self.logdir = logdir
logLevel = logging.DEBUG
logPrefix = "MainThread_TEST" if self.test else "MainThread"
try:
self.logger = getLogger(logPrefix, self.logdir, logLevel, FORMAT)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
os._exit(0)
else:
self.logger.debug("-------------------- MainThread created. Starting __init__() --------------------")
def run(self):
self.logger.debug("Initializing ReportThreads..")
for (group, cfg) in self.config.items():
self.logger.debug(" ------------------------------ GROUP '%s' CONFIG ------------------------------ " % group)
for k2, v2 in cfg.items():
self.logger.debug("%s <==> %s: %s" % (group, k2, v2))
try:
rt = ReportThread(self, group, cfg, self.logdir, self.test)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
self.logger.exception("Exception when creating ReportThread (%s)" % group)
logging.shutdown()
os._exit(1)
else:
self.threads.append(rt)
self.logger.debug("Threads initialized.. \"%s\"" % ", ".join([t.name for t in self.threads]))
for t in self.threads:
t.Start()
if not self.test:
self.loop()
class ReportThread:
def __init__(self, mainThread, name, config, logdir, test):
self.mainThread = mainThread
self.name = name
logLevel = logging.DEBUG
self.logger = getLogger("MainThread%s.ReportThread_%s" % ("_TEST" if self.test else "", self.name), logdir, logLevel, FORMAT)
self.logger.info("init database...")
self.initDB()
# etc....
if __name__ == "__main__":
# .....
MainThread(cfgdefaults=options.cfgdefaults, configdir=options.configdir, pidfile=options.pidfile, logdir=options.logdir, test=options.test)
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Since I haven't found a satisfactory answer, I would like to elaborate on the answer to the question a little bit in order to give some insight into the workings and intents of the `logging` library, that comes with Python's standard library.
In contrast to the approach of the OP (original poster) the library clearly separates the interface to the logger and configuration of the logger itself.
>
> The configuration of handlers is the prerogative of the application developer who uses your library.
>
>
>
That means you should *not* create a custom logger class and configure the logger inside that class by adding any configuration or whatsoever.
The `logging` library introduces four components: *loggers*, *handlers*, *filters*, and *formatters*.
>
> * Loggers expose the interface that application code directly uses.
> * Handlers send the log records (created by loggers) to the appropriate destination.
> * Filters provide a finer grained facility for determining which log records to output.
> * Formatters specify the layout of log records in the final output.
>
>
>
A common project structure looks like this:
```
Project/
|-- .../
| |-- ...
|
|-- project/
| |-- package/
| | |-- __init__.py
| | |-- module.py
| |
| |-- __init__.py
| |-- project.py
|
|-- ...
|-- ...
```
Inside your code (like in **module.py**) you refer to the logger instance of your module to log the events at their specific levels.
>
> A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
>
>
>
```
logger = logging.getLogger(__name__)
```
The special variable `__name__` refers to your module's name and looks something like `project.package.module` depending on your application's code structure.
**module.py** (and any other class) could essentially look like this:
```
import logging
...
log = logging.getLogger(__name__)
class ModuleClass:
def do_something(self):
log.debug('do_something() has been called!')
```
The logger in each module will propagate any event to the parent logger which in return passes the information to its attached *handler*! Analogously to the python package/module structure, the parent logger is determined by the namespace using "dotted module names". That's why it makes sense to initialize the logger with the special `__name__` variable (in the example above **name** matches the string *"project.package.module"*).
There are two options to configure the logger globally:
* Instantiate a logger in **project.py** with the name `__package__` which equals *"project"* in this example and is therefore the parent logger of the loggers of all submodules. It is only necessary to add an appropriate handler and formatter to *this* logger.
* Set up a logger with a handler and formatter in the executing script (like **main.py**) with the name of the topmost package.
>
> When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used.
>
>
>
The executing script, like **main.py** for example, might finally look something like this:
```
import logging
from project import App
def setup_logger():
# create logger
logger = logging.getLogger('project')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
if __name__ == '__main__' and __package__ is None:
setup_logger()
app = App()
app.do_some_funny_stuff()
```
The method call `log.setLevel(...)` specifies the lowest-severity log message a logger will *handle* but not necessarily output! It simply means the message is passed to the handler as long as the message's severity level is higher than (or equal to) the one that is set. But the *handler* is responsible for *handling* the log message (by printing or storing it for example).
Hence the `logging` library offers a structured and modular approach which just needs to be exploited according to one's needs.
[Logging documentation](https://docs.python.org/2/howto/logging.html)
|
You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the `logger = logging.getLogger(loggerName)` part):
```
def getLogger(name, logdir=LOGDIR_DEFAULT, level=logging.DEBUG, logformat=FORMAT):
base = os.path.basename(__file__)
loggerName = "%s.%s" % (base, name)
logFileName = os.path.join(logdir, "%s.log" % loggerName)
logger = logging.getLogger(loggerName)
logger.setLevel(level)
i = 0
while os.path.exists(logFileName) and not os.access(logFileName, os.R_OK | os.W_OK):
i += 1
logFileName = "%s.%s.log" % (logFileName.replace(".log", ""), str(i).zfill((len(str(i)) + 1)))
try:
#fh = logging.FileHandler(logFileName)
fh = RotatingFileHandler(filename=logFileName, mode="a", maxBytes=1310720, backupCount=50)
except IOError, exc:
errOut = "Unable to create/open log file \"%s\"." % logFileName
if exc.errno is 13: # Permission denied exception
errOut = "ERROR ** Permission Denied ** - %s" % errOut
elif exc.errno is 2: # No such directory
errOut = "ERROR ** No such directory \"%s\"** - %s" % (os.path.split(logFileName)[0], errOut)
elif exc.errno is 24: # Too many open files
errOut = "ERROR ** Too many open files ** - Check open file descriptors in /proc/<PID>/fd/ (PID: %s)" % os.getpid()
else:
errOut = "Unhandled Exception ** %s ** - %s" % (str(exc), errOut)
raise LogException(errOut)
else:
formatter = logging.Formatter(logformat)
fh.setLevel(level)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
class MainThread:
def __init__(self, cfgdefaults, configdir, pidfile, logdir, test=False):
self.logdir = logdir
logLevel = logging.DEBUG
logPrefix = "MainThread_TEST" if self.test else "MainThread"
try:
self.logger = getLogger(logPrefix, self.logdir, logLevel, FORMAT)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
os._exit(0)
else:
self.logger.debug("-------------------- MainThread created. Starting __init__() --------------------")
def run(self):
self.logger.debug("Initializing ReportThreads..")
for (group, cfg) in self.config.items():
self.logger.debug(" ------------------------------ GROUP '%s' CONFIG ------------------------------ " % group)
for k2, v2 in cfg.items():
self.logger.debug("%s <==> %s: %s" % (group, k2, v2))
try:
rt = ReportThread(self, group, cfg, self.logdir, self.test)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
self.logger.exception("Exception when creating ReportThread (%s)" % group)
logging.shutdown()
os._exit(1)
else:
self.threads.append(rt)
self.logger.debug("Threads initialized.. \"%s\"" % ", ".join([t.name for t in self.threads]))
for t in self.threads:
t.Start()
if not self.test:
self.loop()
class ReportThread:
def __init__(self, mainThread, name, config, logdir, test):
self.mainThread = mainThread
self.name = name
logLevel = logging.DEBUG
self.logger = getLogger("MainThread%s.ReportThread_%s" % ("_TEST" if self.test else "", self.name), logdir, logLevel, FORMAT)
self.logger.info("init database...")
self.initDB()
# etc....
if __name__ == "__main__":
# .....
MainThread(cfgdefaults=options.cfgdefaults, configdir=options.configdir, pidfile=options.pidfile, logdir=options.logdir, test=options.test)
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
The python logging module is already good enough as global logger, you might simply looking for this:
**main.py**
```
import logging
logging.basicConfig(level = logging.DEBUG,format = '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
```
Put the codes above into your executing script, then you can use this logger with the same configs anywhere in your projects:
**module.py**
```
import logging
logger = logging.getLogger(__name__)
logger.info('hello world!')
```
For more complicated configs you may use a config file **logging.conf** with logging
```
logging.config.fileConfig("logging.conf")
```
|
You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the `logger = logging.getLogger(loggerName)` part):
```
def getLogger(name, logdir=LOGDIR_DEFAULT, level=logging.DEBUG, logformat=FORMAT):
base = os.path.basename(__file__)
loggerName = "%s.%s" % (base, name)
logFileName = os.path.join(logdir, "%s.log" % loggerName)
logger = logging.getLogger(loggerName)
logger.setLevel(level)
i = 0
while os.path.exists(logFileName) and not os.access(logFileName, os.R_OK | os.W_OK):
i += 1
logFileName = "%s.%s.log" % (logFileName.replace(".log", ""), str(i).zfill((len(str(i)) + 1)))
try:
#fh = logging.FileHandler(logFileName)
fh = RotatingFileHandler(filename=logFileName, mode="a", maxBytes=1310720, backupCount=50)
except IOError, exc:
errOut = "Unable to create/open log file \"%s\"." % logFileName
if exc.errno is 13: # Permission denied exception
errOut = "ERROR ** Permission Denied ** - %s" % errOut
elif exc.errno is 2: # No such directory
errOut = "ERROR ** No such directory \"%s\"** - %s" % (os.path.split(logFileName)[0], errOut)
elif exc.errno is 24: # Too many open files
errOut = "ERROR ** Too many open files ** - Check open file descriptors in /proc/<PID>/fd/ (PID: %s)" % os.getpid()
else:
errOut = "Unhandled Exception ** %s ** - %s" % (str(exc), errOut)
raise LogException(errOut)
else:
formatter = logging.Formatter(logformat)
fh.setLevel(level)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
class MainThread:
def __init__(self, cfgdefaults, configdir, pidfile, logdir, test=False):
self.logdir = logdir
logLevel = logging.DEBUG
logPrefix = "MainThread_TEST" if self.test else "MainThread"
try:
self.logger = getLogger(logPrefix, self.logdir, logLevel, FORMAT)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
os._exit(0)
else:
self.logger.debug("-------------------- MainThread created. Starting __init__() --------------------")
def run(self):
self.logger.debug("Initializing ReportThreads..")
for (group, cfg) in self.config.items():
self.logger.debug(" ------------------------------ GROUP '%s' CONFIG ------------------------------ " % group)
for k2, v2 in cfg.items():
self.logger.debug("%s <==> %s: %s" % (group, k2, v2))
try:
rt = ReportThread(self, group, cfg, self.logdir, self.test)
except LogException, exc:
sys.stderr.write("%s\n" % exc)
sys.stderr.flush()
self.logger.exception("Exception when creating ReportThread (%s)" % group)
logging.shutdown()
os._exit(1)
else:
self.threads.append(rt)
self.logger.debug("Threads initialized.. \"%s\"" % ", ".join([t.name for t in self.threads]))
for t in self.threads:
t.Start()
if not self.test:
self.loop()
class ReportThread:
def __init__(self, mainThread, name, config, logdir, test):
self.mainThread = mainThread
self.name = name
logLevel = logging.DEBUG
self.logger = getLogger("MainThread%s.ReportThread_%s" % ("_TEST" if self.test else "", self.name), logdir, logLevel, FORMAT)
self.logger.info("init database...")
self.initDB()
# etc....
if __name__ == "__main__":
# .....
MainThread(cfgdefaults=options.cfgdefaults, configdir=options.configdir, pidfile=options.pidfile, logdir=options.logdir, test=options.test)
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Use [`logging.getLogger(name)`](https://docs.python.org/3/library/logging.html#logging.getLogger) to create a named global logger.
**main.py**
```
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')
import submodule
```
**log.py**
```
import logging
def setup_custom_logger(name):
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger
```
**submodule.py**
```
import logging
logger = logging.getLogger('root')
logger.debug('submodule message')
```
**Output**
```
2011-10-01 20:08:40,049 - DEBUG - main - main message
2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message
```
|
Since I haven't found a satisfactory answer, I would like to elaborate on the answer to the question a little bit in order to give some insight into the workings and intents of the `logging` library, that comes with Python's standard library.
In contrast to the approach of the OP (original poster) the library clearly separates the interface to the logger and configuration of the logger itself.
>
> The configuration of handlers is the prerogative of the application developer who uses your library.
>
>
>
That means you should *not* create a custom logger class and configure the logger inside that class by adding any configuration or whatsoever.
The `logging` library introduces four components: *loggers*, *handlers*, *filters*, and *formatters*.
>
> * Loggers expose the interface that application code directly uses.
> * Handlers send the log records (created by loggers) to the appropriate destination.
> * Filters provide a finer grained facility for determining which log records to output.
> * Formatters specify the layout of log records in the final output.
>
>
>
A common project structure looks like this:
```
Project/
|-- .../
| |-- ...
|
|-- project/
| |-- package/
| | |-- __init__.py
| | |-- module.py
| |
| |-- __init__.py
| |-- project.py
|
|-- ...
|-- ...
```
Inside your code (like in **module.py**) you refer to the logger instance of your module to log the events at their specific levels.
>
> A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
>
>
>
```
logger = logging.getLogger(__name__)
```
The special variable `__name__` refers to your module's name and looks something like `project.package.module` depending on your application's code structure.
**module.py** (and any other class) could essentially look like this:
```
import logging
...
log = logging.getLogger(__name__)
class ModuleClass:
def do_something(self):
log.debug('do_something() has been called!')
```
The logger in each module will propagate any event to the parent logger which in return passes the information to its attached *handler*! Analogously to the python package/module structure, the parent logger is determined by the namespace using "dotted module names". That's why it makes sense to initialize the logger with the special `__name__` variable (in the example above **name** matches the string *"project.package.module"*).
There are two options to configure the logger globally:
* Instantiate a logger in **project.py** with the name `__package__` which equals *"project"* in this example and is therefore the parent logger of the loggers of all submodules. It is only necessary to add an appropriate handler and formatter to *this* logger.
* Set up a logger with a handler and formatter in the executing script (like **main.py**) with the name of the topmost package.
>
> When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used.
>
>
>
The executing script, like **main.py** for example, might finally look something like this:
```
import logging
from project import App
def setup_logger():
# create logger
logger = logging.getLogger('project')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
if __name__ == '__main__' and __package__ is None:
setup_logger()
app = App()
app.do_some_funny_stuff()
```
The method call `log.setLevel(...)` specifies the lowest-severity log message a logger will *handle* but not necessarily output! It simply means the message is passed to the handler as long as the message's severity level is higher than (or equal to) the one that is set. But the *handler* is responsible for *handling* the log message (by printing or storing it for example).
Hence the `logging` library offers a structured and modular approach which just needs to be exploited according to one's needs.
[Logging documentation](https://docs.python.org/2/howto/logging.html)
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Use [`logging.getLogger(name)`](https://docs.python.org/3/library/logging.html#logging.getLogger) to create a named global logger.
**main.py**
```
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')
import submodule
```
**log.py**
```
import logging
def setup_custom_logger(name):
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger
```
**submodule.py**
```
import logging
logger = logging.getLogger('root')
logger.debug('submodule message')
```
**Output**
```
2011-10-01 20:08:40,049 - DEBUG - main - main message
2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message
```
|
The python logging module is already good enough as global logger, you might simply looking for this:
**main.py**
```
import logging
logging.basicConfig(level = logging.DEBUG,format = '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
```
Put the codes above into your executing script, then you can use this logger with the same configs anywhere in your projects:
**module.py**
```
import logging
logger = logging.getLogger(__name__)
logger.info('hello world!')
```
For more complicated configs you may use a config file **logging.conf** with logging
```
logging.config.fileConfig("logging.conf")
```
|
7,621,897
|
I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main python file and create an object like this:
```
self.log = logModule.customLogger(arguments)
```
But obviously, I cannot access this object from other parts of my code.
Am i using a wrong approach? Is there a better way to do this?
|
2011/10/01
|
[
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] |
Since I haven't found a satisfactory answer, I would like to elaborate on the answer to the question a little bit in order to give some insight into the workings and intents of the `logging` library, that comes with Python's standard library.
In contrast to the approach of the OP (original poster) the library clearly separates the interface to the logger and configuration of the logger itself.
>
> The configuration of handlers is the prerogative of the application developer who uses your library.
>
>
>
That means you should *not* create a custom logger class and configure the logger inside that class by adding any configuration or whatsoever.
The `logging` library introduces four components: *loggers*, *handlers*, *filters*, and *formatters*.
>
> * Loggers expose the interface that application code directly uses.
> * Handlers send the log records (created by loggers) to the appropriate destination.
> * Filters provide a finer grained facility for determining which log records to output.
> * Formatters specify the layout of log records in the final output.
>
>
>
A common project structure looks like this:
```
Project/
|-- .../
| |-- ...
|
|-- project/
| |-- package/
| | |-- __init__.py
| | |-- module.py
| |
| |-- __init__.py
| |-- project.py
|
|-- ...
|-- ...
```
Inside your code (like in **module.py**) you refer to the logger instance of your module to log the events at their specific levels.
>
> A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
>
>
>
```
logger = logging.getLogger(__name__)
```
The special variable `__name__` refers to your module's name and looks something like `project.package.module` depending on your application's code structure.
**module.py** (and any other class) could essentially look like this:
```
import logging
...
log = logging.getLogger(__name__)
class ModuleClass:
def do_something(self):
log.debug('do_something() has been called!')
```
The logger in each module will propagate any event to the parent logger which in return passes the information to its attached *handler*! Analogously to the python package/module structure, the parent logger is determined by the namespace using "dotted module names". That's why it makes sense to initialize the logger with the special `__name__` variable (in the example above **name** matches the string *"project.package.module"*).
There are two options to configure the logger globally:
* Instantiate a logger in **project.py** with the name `__package__` which equals *"project"* in this example and is therefore the parent logger of the loggers of all submodules. It is only necessary to add an appropriate handler and formatter to *this* logger.
* Set up a logger with a handler and formatter in the executing script (like **main.py**) with the name of the topmost package.
>
> When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used.
>
>
>
The executing script, like **main.py** for example, might finally look something like this:
```
import logging
from project import App
def setup_logger():
# create logger
logger = logging.getLogger('project')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
if __name__ == '__main__' and __package__ is None:
setup_logger()
app = App()
app.do_some_funny_stuff()
```
The method call `log.setLevel(...)` specifies the lowest-severity log message a logger will *handle* but not necessarily output! It simply means the message is passed to the handler as long as the message's severity level is higher than (or equal to) the one that is set. But the *handler* is responsible for *handling* the log message (by printing or storing it for example).
Hence the `logging` library offers a structured and modular approach which just needs to be exploited according to one's needs.
[Logging documentation](https://docs.python.org/2/howto/logging.html)
|
The python logging module is already good enough as global logger, you might simply looking for this:
**main.py**
```
import logging
logging.basicConfig(level = logging.DEBUG,format = '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
```
Put the codes above into your executing script, then you can use this logger with the same configs anywhere in your projects:
**module.py**
```
import logging
logger = logging.getLogger(__name__)
logger.info('hello world!')
```
For more complicated configs you may use a config file **logging.conf** with logging
```
logging.config.fileConfig("logging.conf")
```
|
69,410,508
|
I wanted to save all the text which I enter in the listbox. "my\_list" is the listbox over here.
But when I save my file, I get the output in the form of a tuple, as shown below:
```
("Some","Random","Values")
```
Below is the python code. I have added comments to it.
The add\_items function adds data into the entry box.
The savefile function is supposed to save all the data entered in the entry box (each entry must be in a new line)
```py
from tkinter import *
from tkinter.font import Font
from tkinter import filedialog
root = Tk()
root.title('TODO List!')
root.geometry("500x500")
name = StringVar()
############### Fonts ################
my_font = Font(
family="Brush Script MT",
size=30,
weight="bold")
################# Frame #################
my_frame = Frame(root)
my_frame.pack(pady=10)
################# List Box #############
my_list = Listbox(my_frame,
font=my_font,
width=25,
height=5,
bg="SystemButtonFace",
bd=0,
fg="#464646",
highlightthickness=0,
selectbackground="grey",
activestyle="none")
my_list.pack(side=LEFT, fill=BOTH)
############### Dummy List ##################
#stuff = ["Do daily Checkin","Do Event checkin","Complete Daily Task","Complete Weekly Task","Take a break"]
############# Add dummmy list to list box ##############
#for item in stuff:
# my_list.insert(END, item)
################# Ceate Scrollbar ###########################
my_scrollbar= Scrollbar(my_frame)
my_scrollbar.pack(side=RIGHT, fill=BOTH)
#################### Add Scrollbar ######################
my_list.config(yscrollcommand=my_scrollbar.set)
my_scrollbar.config(command=my_list.yview)
################### ADD item entry box#################
my_entry = Entry(root, font=("Helvetica", 24),width=24, textvariable=name)
my_entry.pack(pady=20)
######################## Crete button frame ##########
button_frame=Frame(root)
button_frame.pack(pady=20)
##################### Funnctions ###################
def add_item():
my_list.insert(END, my_entry.get())
name1 = name.get()
my_entry.delete(0, END)
def saveFile():
file = filedialog.asksaveasfile(initialdir="C:\\Users\\Deepu John\\OneDrive\\Deepu 2020\\Projects\\rough",
defaultextension='.txt',
filetypes=[
("Text file",".txt"),
("HTML file", ".html"),
("All files", ".*"),
])
if file is None:
return
#fob = open(file,'w')
filetext = str(my_list.get('1', 'end'))
file.write(filetext)
file.close()
def delete_list():
my_list.delete(0,END)
################# Add Buttons ################
add_button = Button(button_frame, text="Add Item",command=add_item)
save_button = Button(button_frame, text="Save",width=8,command=saveFile)
add_button.grid(row=0,column=1, padx=20)
save_button.grid(row=0,column=2,padx=5)
root.mainloop()
```
I want each value to be in a new line. Like this:
```
Some
Random
Values
```
How do I do this?
|
2021/10/01
|
[
"https://Stackoverflow.com/questions/69410508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16781901/"
] |
The main part is that `listbox.get(first, last)` returns a tuple so you could use `.join` string method to create a string where each item in the tuple is separated by the given string:
```py
'\n'.join(listbox.get('0', 'end'))
```
Complete example:
```py
from tkinter import Tk, Entry, Listbox, Button
def add_item(event=None):
item = entry.get() or None
entry.delete('0', 'end')
listbox.insert('end', item)
def save_listbox():
"""the main part:
as `listbox.get(first, last)` returns a tuple
one can simply use the `.join` method
to create a string where each item is separated
by the given string"""
data = '\n'.join(listbox.get('0', 'end'))
with open('my_list.txt', 'w') as file:
file.write(data)
root = Tk()
entry = Entry(root)
entry.pack(padx=10, pady=10)
entry.bind('<Return>', add_item)
listbox = Listbox(root)
listbox.pack(padx=10, pady=10)
button = Button(root, text='Save', command=save_listbox)
button.pack(padx=10, pady=10)
root.mainloop()
```
Also:
I strongly advise against using wildcard (`*`) when importing something, You should either import what You need, e.g. `from module import Class1, func_1, var_2` and so on or import the whole module: `import module` then You can also use an alias: `import module as md` or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.
|
This is a very simple task.
Where you are saving the file, write this code:
```
newlist = []
for item in mylist.get(0, END):
newlist.append(item)
f = open(file, 'w')
for line in newlist:
f.write(line+'\n')
f.close()
```
To know more about file saving in tkinter or to make it much easier, you can check my txtopp repository on GitHub. It is a module I made:
<https://github.com/armaanPYTHON/txt-file-management-module>
|
60,838,550
|
I've written a script in python using selenium to log in to a website and then go on to the target page in order to upload a pdf file. The script can log in successfully but throws `element not interactable` error when it comes to upload the pdf file. This is the [landing\_page](https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/SEARCH/RESULTS/) in which the script first clicks on the button right next to `Your Profile` and uses `SIM.iqbal_123` and `SShift_123` respectively to log in to that site and then uses this [target\_link](https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/2/) to upload that file. To upload that file it is necessary to click on `select` button first and then `cv` button. However, the script throws the following error when it is supposed to click on the `cv` button in order to upload the `pdf` file.
I've tried with:
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
landing_page = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/SEARCH/RESULTS/'
target_link = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/2/'
driver = webdriver.Chrome()
wait = WebDriverWait(driver,30)
driver.get(landing_page)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".profileContainer > button.trigger"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='alias']"))).send_keys("SIM.iqbal_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='password']"))).send_keys("SShift_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button.loginBtn"))).click()
driver.get(target_link)
button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[class*='uploadBtn']")))
driver.execute_script("arguments[0].click();",button)
elem = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"form[class='fileForm'] > label[data-type='12']")))
elem.send_keys("C://Users/WCS/Desktop/CV.pdf")
```
Error that the script encounters pointing at the last line:
```
Traceback (most recent call last):
File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\keep_it.py", line 22, in <module>
elem.send_keys("C://Users/WCS/Desktop/CV.pdf")
File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=80.0.3987.149)
```
This is how I tried using requests which could not upload the file either:
```
import requests
from bs4 import BeautifulSoup
aplication_link = 'https://jobs.allianz.com/sap/opu/odata/hcmx/erc_ui_auth_srv/AttachmentSet?sap-client=100&sap-language=en'
with requests.Session() as s:
s.auth = ("SIM.iqbal_123", "SShift_123")
s.post("https://jobs.allianz.com/sap/hcmx/validate_ea?sap-client=100&sap-language={2}")
r = s.get("https://jobs.allianz.com/sap/opu/odata/hcmx/erc_ui_auth_srv/UserSet('me')?sap-client=100&sap-language=en", headers={'x-csrf-token':'Fetch'})
token = r.headers.get("x-csrf-token")
s.headers["x-csrf-token"] = token
file = open("CV.pdf","rb")
r = s.post(aplication_link,files={"Slug":f"Filename={file}&Title=CV%5FTEST&AttachmentTypeID=12"})
print(r.status_code)
```
Btw, this is the [pdf](https://filebin.net/dc41y5p7ix8jp58t) file in case you wanna test.
>
> How can I upload a pdf file using send\_keys or requests?
>
>
>
***EDIT:***
I've brought about some changes in my [existing script](https://filebin.net/r4ux62fizvyu29ne) which now works for this [link](https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/1/) visible there as `Cover Letter` but fails miserably when it goes for this [link](https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/2/) visible as `Documents` . They both are almost identical.
|
2020/03/24
|
[
"https://Stackoverflow.com/questions/60838550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10568531/"
] |
Please refer below solution to avoid your exception,
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.common.action_chains import ActionChains
import os
landing_page = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/SEARCH/RESULTS/'
target_link = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57262231/2/'
driver = webdriver.Chrome(executable_path=r"C:\New folder\chromedriver.exe")
wait = WebDriverWait(driver,30)
driver.get(landing_page)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".profileContainer > button.trigger"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='alias']"))).send_keys("SIM.iqbal_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='password']"))).send_keys("SShift_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button.loginBtn"))).click()
driver.get(target_link)
driver.maximize_window()
button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[class*='uploadBtn']")))
driver.execute_script("arguments[0].click();",button)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//label[@class='button uploadType-12-btn']")))
print element.text
webdriver.ActionChains(driver).move_to_element(element).click(element).perform()
webdriver.ActionChains(driver).move_to_element(element).click(element).perform()
absolute_file_path = os.path.abspath("Path of your pdf file")
print absolute_file_path
file_input = driver.find_element_by_id("DOCUMENTS--fileElem")
file_input.send_keys(absolute_file_path)
```
**Output:**
[](https://i.stack.imgur.com/9TRU2.png)
|
Try this script , it upload document on both pages
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
landing_page = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/SEARCH/RESULTS/'
first_target_link = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/1/'
second_target_link = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_ui_ex/desktop.html#/APPLICATION/57274787/2/'
driver = webdriver.Chrome()
wait = WebDriverWait(driver,30)
driver.get(landing_page)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".profileContainer > button.trigger"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='alias']"))).send_keys("SIM.iqbal_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[name='password']"))).send_keys("SShift_123")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button.loginBtn"))).click()
#----------------------------first upload starts from here-----------------------------------
driver.get(first_target_link)
button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[class*='uploadBtn']")))
driver.execute_script("arguments[0].click();",button)
element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"form[class='fileForm'] > label[class$='uploadTypeCoverLetterBtn']")))
driver.execute_script("arguments[0].click();",element)
file_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[id='COVERLETTER--fileElem")))
file_input.send_keys("C://Users/WCS/Desktop/script selenium/CV.pdf")
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR,".loadingSpinner")))
save_draft = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".applicationStepsUIWrapper > button.saveDraftBtn")))
driver.execute_script("arguments[0].click();",save_draft)
close = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".promptWrapper button.closeBtn")))
driver.execute_script("arguments[0].click();",close)
#-------------------------second upload starts from here-------------------------------------
driver.get(second_target_link)
button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[class*='uploadBtn']")))
driver.execute_script("arguments[0].click();",button)
element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"form[class='fileForm'] > label[data-type='12']")))
driver.execute_script("arguments[0].click();",element)
file_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"input[id='DOCUMENTS--fileElem")))
file_input.send_keys("C://Users/WCS/Desktop/script selenium/CV.pdf")
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR,".loadingSpinner")))
save_draft = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".applicationStepsUIWrapper > button.saveDraftBtn")))
driver.execute_script("arguments[0].click();",save_draft)
close = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".promptWrapper button.closeBtn")))
driver.execute_script("arguments[0].click();",close)
```
|
16,505,752
|
I collected some tweets through twitter api. Then I counted the words using `split(' ')` in python. However, some words appear like this:
```
correct!
correct.
,correct
blah"
...
```
So how can I format the tweets without punctuation? Or maybe I should try another way to `split` tweets? Thanks.
|
2013/05/12
|
[
"https://Stackoverflow.com/questions/16505752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975222/"
] |
You can do the split on multiple characters using `re.split`...
```
from string import punctuation
import re
puncrx = re.compile(r'[{}\s]'.format(re.escape(punctuation)))
print filter(None, puncrx.split(your_tweet))
```
Or, just find words that contain certain contiguous characters:
```
print re.findall(re.findall('[\w#@]+', s), your_tweet)
```
eg:
```
print re.findall(r'[\w@#]+', 'talking about #python with @someone is so much fun! Is there a 140 char limit? So not cool!')
# ['talking', 'about', '#python', 'with', '@someone', 'is', 'so', 'much', 'fun', 'Is', 'there', 'a', '140', 'char', 'limit', 'So', 'not', 'cool']
```
I did originally have a smiley in the example, but of course these end up getting filtered out with this method, so that's something to be wary of.
|
Try removing the punctuation from the string before doing the split.
```
import string
s = "Some nice sentence. This has punctuation!"
out = s.translate(string.maketrans("",""), string.punctuation)
```
Then do the `split` on `out`.
|
16,505,752
|
I collected some tweets through twitter api. Then I counted the words using `split(' ')` in python. However, some words appear like this:
```
correct!
correct.
,correct
blah"
...
```
So how can I format the tweets without punctuation? Or maybe I should try another way to `split` tweets? Thanks.
|
2013/05/12
|
[
"https://Stackoverflow.com/questions/16505752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975222/"
] |
You can do the split on multiple characters using `re.split`...
```
from string import punctuation
import re
puncrx = re.compile(r'[{}\s]'.format(re.escape(punctuation)))
print filter(None, puncrx.split(your_tweet))
```
Or, just find words that contain certain contiguous characters:
```
print re.findall(re.findall('[\w#@]+', s), your_tweet)
```
eg:
```
print re.findall(r'[\w@#]+', 'talking about #python with @someone is so much fun! Is there a 140 char limit? So not cool!')
# ['talking', 'about', '#python', 'with', '@someone', 'is', 'so', 'much', 'fun', 'Is', 'there', 'a', '140', 'char', 'limit', 'So', 'not', 'cool']
```
I did originally have a smiley in the example, but of course these end up getting filtered out with this method, so that's something to be wary of.
|
I would advice to clean text from special symbols before splitting it using this code:
```
tweet_object["text"] = re.sub(u'[!?@#$.,#:\u2026]', '', tweet_object["text"])
```
You would need to import re before using function sub
```
import re
```
|
56,399,448
|
I have the following code which sums up values of each key. I am trying to use the list in the reducer since my actual use case is to sample values of each key. I get the error I show below? How do I achieve with a list(or tuple). I always get my data in the form of tensors and need to use tensorflow to achieve the reduction.
Raw data
```
ids | features
--------------
1 | 1
2 | 2.2
3 | 7
1 | 3.0
2 | 2
3 | 3
```
Desired data
```
ids | features
--------------
1 | 4
2 | 4.2
3 | 10
```
Tensorflow code
```
import tensorflow as tf
tf.enable_eager_execution()
# this is a toy example. My inputs are always passed as tensors.
ids = tf.constant([1, 2, 3, 1, 2, 3])
features = tf.constant([1, 2.2, 7, 3.0, 2, 3])
# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
return []
def reduce_func(state, value):
# I actually want to sample 2 values from list but for simplicity here I return sum
return state + value['features']
def finalize_func(state):
return np.sum(state)
reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)
# Group by reducer
# Group the data by id
def key_f(row):
return tf.to_int64(row['ids'])
t = tf.contrib.data.group_by_reducer(
key_func = key_f,
reducer = reducer)
ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)
iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)
```
Following is the error I get
```
/home/lyft/venv/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.pyc in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, defun_kwargs)
2122 self._function = tf_data_structured_function_wrapper
2123 if add_to_graph:
-> 2124 self._function.add_to_graph(ops.get_default_graph())
2125 else:
2126 # Use the private method that will execute
AttributeError: '_OverloadedFunction' object has no attribute 'add_to_graph'
```
|
2019/05/31
|
[
"https://Stackoverflow.com/questions/56399448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418127/"
] |
What you can do to mock your store is
```
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// in this point store.getState is going to be mocked
store.getState = () => mockState
test('sampleFunction returns true', () => {
// assert that state.foo.isGood = true
expect(sampleFunction()).toBeTruthy();
});
```
|
```
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
beforeAll(() => {
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// making getState as mock function and returning mock value
store.getState = jest.fn().mockReturnValue(mockState)
});
afterAll(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
test('sampleFunction returns true', () => {
// assert that state.foo.isGood = true
expect(sampleFunction()).toBeTruthy();
});
```
|
36,620,656
|
I am trying to learn how to write a script `control.py`, that runs another script `test.py` in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once `test.py` has finished, either on its own, or by force). So something along the lines:
```
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
```
* The problem with the above is that, it does not check the output of `test.py` as it is running, instead it waits until `test.py` process is finished on its own, right?
* Basically trying to learn how I can use a python script to control another one, as it is running. (e.g. having access to what it prints and so on).
* Finally, is it possible to run `test.py` in a new terminal (i.e. not in `control.py`'s terminal) and still achieve the above goals?
---
**An attempt:**
`test.py` is this:
```
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
```
And `control.py` is this: (following Marc's suggestion)
```
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code
```
|
2016/04/14
|
[
"https://Stackoverflow.com/questions/36620656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You can use subprocess module or also the os.popen
```
os.popen(command[, mode[, bufsize]])
```
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.
With subprocess I would suggest
```
subprocess.call(['python.exe', command])
```
or the subprocess.Popen --> that is similar to os.popen (for instance)
With popen you can read the connected object/file and check whether "Stop now" is there.
The os.system is not deprecated and you can use as well (but you won't get a object from that), you can just check if return at the end of execution.
From subprocess.call you can run it in a new terminal or if you want to call multiple times ONLY the test.py --> than you can put your script in a def main() and run the main as much as you want till the "Stop now" is generated.
Hope this solve your query :-) otherwise comment again.
Looking at what you wrote above you can also redirect the output to a file directly from the OS call --> os.system(test.py \*args >> /tmp/mickey.txt) then you can check at each round the file.
As said the popen is an object file that you can access.
|
You can use the "subprocess" library for that.
```
import subprocess
command = ["python", "test.py", "someargument"]
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not None:
break
if output == 'stop now':
#Do whatever you want
rc = p.poll() #Exit Code
```
|
36,620,656
|
I am trying to learn how to write a script `control.py`, that runs another script `test.py` in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once `test.py` has finished, either on its own, or by force). So something along the lines:
```
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
```
* The problem with the above is that, it does not check the output of `test.py` as it is running, instead it waits until `test.py` process is finished on its own, right?
* Basically trying to learn how I can use a python script to control another one, as it is running. (e.g. having access to what it prints and so on).
* Finally, is it possible to run `test.py` in a new terminal (i.e. not in `control.py`'s terminal) and still achieve the above goals?
---
**An attempt:**
`test.py` is this:
```
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
```
And `control.py` is this: (following Marc's suggestion)
```
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code
```
|
2016/04/14
|
[
"https://Stackoverflow.com/questions/36620656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What you are hinting at in your comment to Marc Cabos' answer is [Threading](https://docs.python.org/3/library/threading.html)
There are several ways Python can use the functionality of other files. If the content of `test.py` can be encapsulated in a function or class, then you can `import` the relevant parts into your program, giving you greater access to the runnings of that code.
As described in other answers you can use the stdout of a script, running it in a subprocess. This could give you separate terminal outputs as you require.
However if you want to run the `test.py` *concurrently* and access variables as they are changed then you need to consider threading.
|
You can use the "subprocess" library for that.
```
import subprocess
command = ["python", "test.py", "someargument"]
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not None:
break
if output == 'stop now':
#Do whatever you want
rc = p.poll() #Exit Code
```
|
36,620,656
|
I am trying to learn how to write a script `control.py`, that runs another script `test.py` in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once `test.py` has finished, either on its own, or by force). So something along the lines:
```
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
```
* The problem with the above is that, it does not check the output of `test.py` as it is running, instead it waits until `test.py` process is finished on its own, right?
* Basically trying to learn how I can use a python script to control another one, as it is running. (e.g. having access to what it prints and so on).
* Finally, is it possible to run `test.py` in a new terminal (i.e. not in `control.py`'s terminal) and still achieve the above goals?
---
**An attempt:**
`test.py` is this:
```
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
```
And `control.py` is this: (following Marc's suggestion)
```
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code
```
|
2016/04/14
|
[
"https://Stackoverflow.com/questions/36620656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You can use subprocess module or also the os.popen
```
os.popen(command[, mode[, bufsize]])
```
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.
With subprocess I would suggest
```
subprocess.call(['python.exe', command])
```
or the subprocess.Popen --> that is similar to os.popen (for instance)
With popen you can read the connected object/file and check whether "Stop now" is there.
The os.system is not deprecated and you can use as well (but you won't get a object from that), you can just check if return at the end of execution.
From subprocess.call you can run it in a new terminal or if you want to call multiple times ONLY the test.py --> than you can put your script in a def main() and run the main as much as you want till the "Stop now" is generated.
Hope this solve your query :-) otherwise comment again.
Looking at what you wrote above you can also redirect the output to a file directly from the OS call --> os.system(test.py \*args >> /tmp/mickey.txt) then you can check at each round the file.
As said the popen is an object file that you can access.
|
Yes you can use Python to control another program using stdin/stdout, but when using another process output often there is a problem of buffering, in other words the other process doesn't really output anything until it's done.
There are even cases in which the output is buffered or not depending on if the program is started from a terminal or not.
If you are the author of both programs then probably is better using another interprocess channel where the flushing is explicitly controlled by the code, like sockets.
|
36,620,656
|
I am trying to learn how to write a script `control.py`, that runs another script `test.py` in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once `test.py` has finished, either on its own, or by force). So something along the lines:
```
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
```
* The problem with the above is that, it does not check the output of `test.py` as it is running, instead it waits until `test.py` process is finished on its own, right?
* Basically trying to learn how I can use a python script to control another one, as it is running. (e.g. having access to what it prints and so on).
* Finally, is it possible to run `test.py` in a new terminal (i.e. not in `control.py`'s terminal) and still achieve the above goals?
---
**An attempt:**
`test.py` is this:
```
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
```
And `control.py` is this: (following Marc's suggestion)
```
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code
```
|
2016/04/14
|
[
"https://Stackoverflow.com/questions/36620656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What you are hinting at in your comment to Marc Cabos' answer is [Threading](https://docs.python.org/3/library/threading.html)
There are several ways Python can use the functionality of other files. If the content of `test.py` can be encapsulated in a function or class, then you can `import` the relevant parts into your program, giving you greater access to the runnings of that code.
As described in other answers you can use the stdout of a script, running it in a subprocess. This could give you separate terminal outputs as you require.
However if you want to run the `test.py` *concurrently* and access variables as they are changed then you need to consider threading.
|
Yes you can use Python to control another program using stdin/stdout, but when using another process output often there is a problem of buffering, in other words the other process doesn't really output anything until it's done.
There are even cases in which the output is buffered or not depending on if the program is started from a terminal or not.
If you are the author of both programs then probably is better using another interprocess channel where the flushing is explicitly controlled by the code, like sockets.
|
13,238,357
|
I face a problem when using Scrapy + Mongodb with Tor. I get the following error when I try to have a mongodb pipeline in Scrapy.
```
2012-11-05 13:41:14-0500 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
|S-chain|-<>-127.0.0.1:9050-<><>-127.0.0.1:27017-<--denied
Traceback (most recent call last):
File "/usr/bin/scrapy", line 4, in <module>
execute()
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 131, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 97, in _run_print_help
func(*a, **kw)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 138, in _run_command
cmd.run(args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/commands/crawl.py", line 42, in run
q = self.crawler.queue
File "/usr/lib/python2.7/dist-packages/scrapy/command.py", line 33, in crawler
self._crawler.configure()
File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 43, in configure
self.engine = ExecutionEngine(self.settings, self._spider_closed)
File "/usr/lib/python2.7/dist-packages/scrapy/core/engine.py", line 33, in __init__
self.scraper = Scraper(self, self.settings)
File "/usr/lib/python2.7/dist-packages/scrapy/core/scraper.py", line 66, in __init__
self.itemproc = itemproc_cls.from_settings(settings)
File "/usr/lib/python2.7/dist-packages/scrapy/middleware.py", line 33, in from_settings
mw = mwcls()
File "/home/bharani/ABCD_scraper/political_forum_scraper/pipelines.py", line 9, in __init__
settings['MONGODB_PORT'])
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
I am not sure how to resolve this. When I do not use `proxychains`, it crawls perfectly fine.
Any help is appreciated.
Thanks.
---
Edit:
It's not code specific. See this link: <http://isbullsh.it/2012/04/Web-crawling-with-scrapy/>
This is a simple tutorial to use `Scrapy` with `MongoDB`. We are supposed to call
`scrapy crawl isbullshit`
to run the crawler which works perfectly fine. To use `Tor`, it should be called like this:
`proxychains scrapy crawl isbullshit`
Which does not work for me. The source code of the tutorial is here: <https://github.com/BaltoRouberol/isbullshit-crawler>
|
2012/11/05
|
[
"https://Stackoverflow.com/questions/13238357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139909/"
] |
```
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
It seems you cannot connect to the localhost on port 27017. Is this the correct port and correct host? Make sure about that, also make sure mongodb server is running on the background otherwise you will never connect it.
If mongodb is running in the background, remove the mongodb.lock
```
rm -r/var/lib/mongodb
```
and restart the server, something like;
```
sudo service mongodb start
```
in Debian or
```
sudo systemctl restart mongodb
```
in Arch Linux
|
It might be that it's trying to redirect your MongoDB connection (localhost:27017) to TOR. If you want to exclude localhost connections from proxychains, you can add the following line to your */etc/proxychains.conf*:
```
localnet 127.0.0.1 000 255.255.255.255
```
|
13,238,357
|
I face a problem when using Scrapy + Mongodb with Tor. I get the following error when I try to have a mongodb pipeline in Scrapy.
```
2012-11-05 13:41:14-0500 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
|S-chain|-<>-127.0.0.1:9050-<><>-127.0.0.1:27017-<--denied
Traceback (most recent call last):
File "/usr/bin/scrapy", line 4, in <module>
execute()
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 131, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 97, in _run_print_help
func(*a, **kw)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 138, in _run_command
cmd.run(args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/commands/crawl.py", line 42, in run
q = self.crawler.queue
File "/usr/lib/python2.7/dist-packages/scrapy/command.py", line 33, in crawler
self._crawler.configure()
File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 43, in configure
self.engine = ExecutionEngine(self.settings, self._spider_closed)
File "/usr/lib/python2.7/dist-packages/scrapy/core/engine.py", line 33, in __init__
self.scraper = Scraper(self, self.settings)
File "/usr/lib/python2.7/dist-packages/scrapy/core/scraper.py", line 66, in __init__
self.itemproc = itemproc_cls.from_settings(settings)
File "/usr/lib/python2.7/dist-packages/scrapy/middleware.py", line 33, in from_settings
mw = mwcls()
File "/home/bharani/ABCD_scraper/political_forum_scraper/pipelines.py", line 9, in __init__
settings['MONGODB_PORT'])
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
I am not sure how to resolve this. When I do not use `proxychains`, it crawls perfectly fine.
Any help is appreciated.
Thanks.
---
Edit:
It's not code specific. See this link: <http://isbullsh.it/2012/04/Web-crawling-with-scrapy/>
This is a simple tutorial to use `Scrapy` with `MongoDB`. We are supposed to call
`scrapy crawl isbullshit`
to run the crawler which works perfectly fine. To use `Tor`, it should be called like this:
`proxychains scrapy crawl isbullshit`
Which does not work for me. The source code of the tutorial is here: <https://github.com/BaltoRouberol/isbullshit-crawler>
|
2012/11/05
|
[
"https://Stackoverflow.com/questions/13238357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139909/"
] |
```
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
It seems you cannot connect to the localhost on port 27017. Is this the correct port and correct host? Make sure about that, also make sure mongodb server is running on the background otherwise you will never connect it.
If mongodb is running in the background, remove the mongodb.lock
```
rm -r/var/lib/mongodb
```
and restart the server, something like;
```
sudo service mongodb start
```
in Debian or
```
sudo systemctl restart mongodb
```
in Arch Linux
|
Open mongo connection before setting the socks proxy
|
13,238,357
|
I face a problem when using Scrapy + Mongodb with Tor. I get the following error when I try to have a mongodb pipeline in Scrapy.
```
2012-11-05 13:41:14-0500 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
|S-chain|-<>-127.0.0.1:9050-<><>-127.0.0.1:27017-<--denied
Traceback (most recent call last):
File "/usr/bin/scrapy", line 4, in <module>
execute()
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 131, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 97, in _run_print_help
func(*a, **kw)
File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 138, in _run_command
cmd.run(args, opts)
File "/usr/lib/python2.7/dist-packages/scrapy/commands/crawl.py", line 42, in run
q = self.crawler.queue
File "/usr/lib/python2.7/dist-packages/scrapy/command.py", line 33, in crawler
self._crawler.configure()
File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 43, in configure
self.engine = ExecutionEngine(self.settings, self._spider_closed)
File "/usr/lib/python2.7/dist-packages/scrapy/core/engine.py", line 33, in __init__
self.scraper = Scraper(self, self.settings)
File "/usr/lib/python2.7/dist-packages/scrapy/core/scraper.py", line 66, in __init__
self.itemproc = itemproc_cls.from_settings(settings)
File "/usr/lib/python2.7/dist-packages/scrapy/middleware.py", line 33, in from_settings
mw = mwcls()
File "/home/bharani/ABCD_scraper/political_forum_scraper/pipelines.py", line 9, in __init__
settings['MONGODB_PORT'])
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 290, in __init__
self.__find_node()
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 586, in __find_node
raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
I am not sure how to resolve this. When I do not use `proxychains`, it crawls perfectly fine.
Any help is appreciated.
Thanks.
---
Edit:
It's not code specific. See this link: <http://isbullsh.it/2012/04/Web-crawling-with-scrapy/>
This is a simple tutorial to use `Scrapy` with `MongoDB`. We are supposed to call
`scrapy crawl isbullshit`
to run the crawler which works perfectly fine. To use `Tor`, it should be called like this:
`proxychains scrapy crawl isbullshit`
Which does not work for me. The source code of the tutorial is here: <https://github.com/BaltoRouberol/isbullshit-crawler>
|
2012/11/05
|
[
"https://Stackoverflow.com/questions/13238357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139909/"
] |
It might be that it's trying to redirect your MongoDB connection (localhost:27017) to TOR. If you want to exclude localhost connections from proxychains, you can add the following line to your */etc/proxychains.conf*:
```
localnet 127.0.0.1 000 255.255.255.255
```
|
Open mongo connection before setting the socks proxy
|
48,734,784
|
so im working on this code for school and i dont know much about python. Can someone tell me why my loop keeps outputting invalid score when the input is part of the valid scores. So if i enter 1, it will say invalid score but it should be valid because i set the variable valid\_scores= [0,1,2,3,4,5,6,7,8,9,10].
This code has to allow the user to enter 5 inputs for six different groups and then add to a list which will find the sum of the list and the avarage of the list.
Code:
```
valid_scores =[0,1,2,3,4,5,6,7,8,9,10]
for group in groups:
scores_for_group = []
valid_scores_loops=0
print("What do you score for group {group_name} as a player?"\
.format(group_name=group))
while valid_scores_loops < 5:
valid_scores=True
player_input =input("* ")
if player_input==valid_scores:
player1.append(player_input)
scores_for_player.append(int(player_input))
else:
if player_input!=valid_scores:
valid_scores= False
print("Invalid score!")
```
|
2018/02/11
|
[
"https://Stackoverflow.com/questions/48734784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9346720/"
] |
The error means that the 3rd line is not well-formed: you need a (*blank space*) between `android:id` value and `android:title` key.
This is the correct XML:
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Profile" android:title="Profile" android:icon="@drawable/ic_person_black_24dp" />
<item android:id="@+id/TradingHistory" android:title="TradingHistory" android:icon="@drawable/ic_history_black_24dp" />
<item android:id="@+id/News" android:title="News" android:icon="@drawable/ic_view_list_black_24dp" />
</menu>
```
|
Go to code in the toolbar and click on reformat code.
|
19,855,110
|
I am learning how to use Selenium in `python` and I try to modify a `css` style on <http://www.google.com>.
For example, the `<span class="gbts"> ....</span>` on that page.
I would like to modify the `gbts` class.
```
browser.execute_script("q = document.getElementById('gbts');" + "q.style.border = '1px solid red';")
```
Is there an API method called `getElementByClass('gbts')` ?
|
2013/11/08
|
[
"https://Stackoverflow.com/questions/19855110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073181/"
] |
You are asking how to get an element by it's CSS class using JavaScript. Nothing to do with Selenium *really*.
Regardless, you have a few options. You can first grab the element using Selenium (so here, yes, Selenium is relevant):
```
element = driver.find_element_by_class_name("gbts")
```
With a reference to this element already, it's then very easy to give it a border:
```
driver.execute_script("arguments[0].style.border = '1px solid red';")
```
(Note, the `arguments[0]`)
If you really must use JavaScript and JavaScript alone, then you are very limited. This is because there is no `getElementByClassName` function within JavaScript. Only `getElementsByClassName` which means it would return a *list* of elements that match a given class.
So you must specifically target what element within the list, that is returned, you want to change. If I wanted to change the *very first* element that had a class of `gbts`, I'd do:
```
driver.execute_script("document.getElementsByClassName('gbts')[0].style.border = '1px solid red';")
```
I would suggest you go for the first option, which means you have Selenium do the leg work for you.
|
Another pure JavaScript option which you may find gives you more flexibility is to use `document.querySelector()`.
Not only will it automatically select the first item from the results set for you, but additionally say you have multiple elements with that class name, but you know that there is only one element with that class name within a certain parent element, you can restrict the search to within that parent element, e.g. `document.querySelector("#parent-div .gbts")`.
See the [(Mozilla documentation)](https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector) for more info.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.