Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi

I have my pygame ready and I'm going to start being a coding-personal-trainer teacher for nearby kids.
No doubt, there are many books for me to gain wisdom on how to proceed? Or, is there a good web-site done?
I asked some previous questions in this sphere, but some additional references/syllabus would be useful.
Thanks
0
[Webinar On Demand] Database Backup and Recovery
LVL 11
[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Hi experts.
Would like to save the content to a file rather than displaying it from python script. Since I'm new to python pls help me
Have attached a python script. right now it prints the content to stdout.

# I think, this line
self._display.display(json.dumps(output, indent=4, sort_keys=True))

Open in new window


Is it possible to have a variable declared for directory for json file location and write the file there?

Source File location:
https://codeclimate.com/github/ansible/ansible/lib/ansible/plugins/callback/json.py

thanks in advance.
json.py
0
Dear all,
I created an exe file using pyinstaller with --noconsole argument and it works fine (No console is shown on click)...
I added it to the windows  task scheduler and got it working onlogon (tried instantly and with a minute delay) but the problem is the task shows the exe console (a BLANK command-prompt-like black screen with the exe location on top) for a couple of seconds and disappears :-( I tried to change the runas user to system but the exe fails as it needs to run as the user...
Can anyone help me with this problem...
0
Dear all,
I wrote a code using python than consists of a couple of processes popens some FTPs and works fine!
I used pyinstaller --onefile --noconsole and created an exe file which still works as planned.
My goal is to add it to the windows startup 7, 8.1 and 10 and I should do it in 250 laptops at work.
I put it in %TEMP% folder and still works on click!
The problem is when I add it to "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" it gives me an error that the script fails!!!!
but when I add it to the start menu's startup it works fine! have anyone noticed the problem!!!
It is driving me crazy
Note 1: I tried other directories
Note 2: I tried run as admin
0
So I'm embarking on a new adventure, that of learning Python, and I'm trying to get some insights on...well, the questions I don't know enough to ask. So here's a list of what I'm trying to accomplish and perspectives/suggestions I'm hoping to gather from the EE community:

Your thoughts on:
  1. Embracing an incredibly loose language (I'm not used to that).
  2. Picking up learning techniques and perspectives which:
        a. Lend themselves to writing code for a broad variety of settings (ie. AI development, microcontroller coding (RPi, Arduino), robotics, IOT). I don't want find out later that I've wasted my time (eg. find out that I should have stuck with Python inside Visual Studio instead of going to the trouble of learning Pycharm -- or a similar kind of misstep).
  3. Biggest surprises and gotcha's coming from the .NET world to Python.  
  4. Anything else you can think of that I really need to know to make Python easier to pick up and make me the most versatile Python coder I can be.

By the way, I've not done any Raspberry Pi or Arduino coding yet (or AI stuff) yet. I'm a programmer by trade, just not in those areas.
0
Years ago, I learned Sed and Awk to complete a project in telecom. Today, I do not recall any aspect of those languages. But am about to learn Perl and have been told that Perl is based on Sed and Awk.

Is that true?

And how are they similar?

Once I start hearing these details, I suspect I will recall a few things about how and why I used Sed and Awk.

Thanks.
0
Hi , I am a python beginner,

When i call this script it turns on a led light, but when i try to turn on a second or third light, the first light turns off. It will only turn on one light at a time and turns off the prior light. How can i turn on all 3 lights at the same time? Thank you!

The Call from command line
sudo python /home/pi/Desktop/light_0.py pin23 on

Open in new window


The script
#!/usr/bin/python
 
import RPi.GPIO as GPIO        #This line alone caused 90 minutes of frustration
import sys
import time
import fcntl  #To lock this script

#Begin to lock the file
pid_file = 'LOCKFILE-FOR-THIS-SCRIPT.pid'
fh = open(pid_file, 'w')

try:
    fcntl.lockf(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running
    print ('Error: Another instance is running...')
    sys.exit(0)

# FOLLOWING IS THE NORMAL CODE 
 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
 
GPIO.setup(23, GPIO.OUT) #set pin 21 to output
GPIO.setup(24, GPIO.OUT) #set pin 21 to output
GPIO.setup(25, GPIO.OUT) #set pin 21 to output
 
pin23 = GPIO.PWM(23, 100)        #set the PWM on pin 25 to 100 hrz / full power
pin24 = GPIO.PWM(24, 100)        #set the PWM on pin 25 to 100 hrz / full power
pin25 = GPIO.PWM(25, 100)        #set the PWM on pin 25 to 100 hrz / full power
 
pin23.start(0) #start the pwm at 0 percent power
pin24.start(0) #start the pwm at 0 percent power
pin25.start(0) #start the pwm at 0 percent power

LOOKUP = {
    "pin23": pin23,
    "pin24": pin24,

Open in new window

0
I need to add the variable var2 to a function:

This does not work:
var2 = pin25
var2+.start(100)

Open in new window


This does work:
pin25.start(100)

Open in new window

0
I made a Python script to turn on and off a light. I call it from another script and pass a variable of 'on' or 'off' from a PHP script.  Its sometimes blinks the light on for a second, sometimes it turns it on. But its not working right. Is the script conflicting itself?

Im new to Python, do i need to quit or exit the script after im done running it?

My python script:
#!/usr/bin/python

import RPi.GPIO as GPIO        #This line alone caused 90 minutes of frustration
import sys
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(25, GPIO.OUT) #set pin 21 to output

p = GPIO.PWM(25,100)        #set the PWM on pin 25 to 100 hrz / full power

p.start(0) #I dont remember what this does but trust me you need it.

var1 = sys.argv[1] #get the variable sent from php on/off

print (var1)

if var1 == ('on'):
    p.ChangeDutyCycle(100)	
    print ("was turned on")
elif var1 == ('off'):
    p.ChangeDutyCycle(0)
    print ("was turned off")

Open in new window


These are attached to a button in PHP, i press it on and off fast and it works 5% of the time:
shell_exec("sudo python /home/pi/Desktop/light.py 'on' ")
shell_exec("sudo python /home/pi/Desktop/light.py 'off' ")

Open in new window

0
Here in the code I have a function name 'boundry' my problem is that when I call this function nothing happens but when i copy the code and use it without the function it works so.....WHAT IS THE PROBLEM?

def boundry(padx,padx_change):
    if padx < 0:
       padx_change = 10

while True:

 for event in pygame.event.get():
    if event.type == pygame.QUIT:
            pygame.quit()
    if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                padx_change = -10
            elif event.key == pygame.K_RIGHT:
                padx_change = 10
    elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                 padx_change = 0
                 
boundry(padx,padx_change)
## if padx < 0:
##       padx_change = 10
 padx += padx_change
 gamedisplay.fill(colours['mixed'])
 draw(gamedisplay,bat,padx,pady)
 pygame.display.update()
 clock.tick(fps)

Open in new window

0
[Webinar] Database Backup and Recovery
LVL 11
[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Trying to get a report from a csv file.

csv file: servers.csv
name,date,zone
server1,3/3/2016,dmz
server2,4/3/2017,prod
server3,4/4/2017,nonprod
server4,6/6/2017,prod

I'm trying to get a list of prod servers that contains the server name and zone.
0
so i'm working on a school project in python for which the app needs to actively detect the presence of a email (with a specific subject but no specific sender). the app also needs to be able to read the email's body.  tutorials on the internet haven't helped too much. is there a way to do this passively(without hindering the rest of the code) using imap or poplib?
0
Hello,

I'm fairly new to using API's, so bear with me here.

Using Postman, I'm able to make a Put request using JSON and it works fine. When I try to use the same JSON body in Python, I am getting this error:

{'code': 'E.Internal', 'error': 'An internal error has occurred processing your request. Please notify Customer Support for assistance.', 'status': 'error'}

The company's customer support is not too helpful so I wanted to see if someone here could help me instead.

Here is my script:

url = 'https://website.com/rest/site/' + record_id

json_body = (JSON body here, same one that works in Postman)
head = {'Accept':'application/json', 'Content-Type': 'application/json'}
             
response = requests.put(url, auth=(username, password), json=json_body, headers=head)
data = response.json()
print(data)

Open in new window


If I change the requests.put to requests.get and drop everything after "auth=(username, password)" it works fine and returns the json of the record. What exactly am I doing wrong and how do I put in the data?
0
import serial

import os, time
 
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)

# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
 
port.write('AT'+'\r\n')
rcv = port.read(10)
print (rcv)

Open in new window

Hi, I am trying to establish communication raspberry pi 3 with SIM 900. I am facing encode issues. I did try many solution from online but didn't get through. the code are as follows with compile results; Please do advice, thanks.
-------------------------------------------------------------------------------------------------------------------
>>> 
======================= RESTART: /home/pi/my_serial.py =======================
Traceback (most recent call last):
  File "/home/pi/my_serial.py", line 11, in <module>
    port.write('AT'+'\r\n')
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 63, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: 'AT\r\n'
>>>
0
Hi
I am nearly ready to begin my foray into games in Python. However, is it more advisable to incorporate a JFrame for the game Window? Is Python GUI up to speed?

Thanks
0
Hi folks,

I have a piece of code that is trying to read out member details from a file and then use a date in that file together with today's date to work out the approximate difference in months (I have not yet started to tackle the exact days in a given month yet) and see if they are over 12 months therefore I can class them as an 'overdue' payment.

I have tried a number of different ways and seem to end up looping around back to TypeError: an integer is required (got type str).

I have attached a cut down version with just the part of the code with an error. I think the issues is within these following lines however I could be wrong:

d = datetime.datetime.now()

lastdatepaid = int(datetime.datetime("%Y-%m-%d"))

newldp = datetime.datetime.strptime(lastdatepaid,"%Y-%m-%d").date()

datechange =(d - lastdatepaid).days

It might help to have the JSON file data:

[[{"DOB:": "2001-11-17", "FeeType:": "SP", "Firstname:": "Joe", "Last Date Paid:": "2016-11-01", "Money Owed: \u00a3": 100, "Months Overdue:": 0, "Months til Overdue:": 12, "Surname:": "Bloggs", "Times Overdue:": 1}]]

N.B. Not all aspects of the project are fully completed but this is my biggest problem I have not been able to solve.

Thank you very much in advance for you help.
Cut-down-version.py
0
Hello

How can I print the output of an element to a text file using xml.etree.elementtree from https://docs.python.org/2/library/xml.etree.elementtree.html

Please look at the first FOR loop section. In the example below I want to print or pipe child.tag and child.attrib to separate files.

>>> for child in root:
...     print child.tag, child.attrib

Open in new window

0
does any one have simple code for testing  DOS for python ?
0
good day, I am testing serial port communciation on raspberry pi 3 interface with SIM 900 module. The code are attached with error message. Thanks

import serial
import os, time
 
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)
 
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
 
port.write('AT'+'\r\n')
rcv = port.read(10)
print (rcv)

>>> 
======================== RESTART: /home/pi/SIM900.py ========================
Traceback (most recent call last):
  File "/home/pi/SIM900.py", line 1, in <module>
    import serial
  File "/home/pi/serial.py", line 5, in <module>
    port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)
AttributeError: module 'serial' has no attribute 'Serial'
>>>
0
Free Tool: Site Down Detector
LVL 11
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

How to install SMTP and MSQLDB package in Python 3

I already use pip command but it says error :
pip install smtplib
Collecting smtplib
  Could not find a version that satisfies the requirement smtplib (from versions: )
No matching distribution found for smtplib

C:\Users\133586>easy_install smtplib
Searching for smtplib
Reading https://pypi.python.org/simple/smtplib/
Couldn't find index page for 'smtplib' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
No local packages or working download links found for smtplib
error: Could not find suitable distribution for Requirement.parse('smtplib')

...

Please help
0
Hi, I am monitoring weather status remotely. I am intend to use Huawei E303F -usb dongle to push data. I did try sakis3g, doesn't help auto-connection after restart. please do assist me how to set internet connection automatically after restart and network down.
0
I am learning the BigO notation and I have a question which is related to homework:

def __str__(self):
return str(self.list)

Open in new window


If I cast an object, does Python iterate over it?
That is, would I have a O(n) here or is it just O(1)?

Thanks for your help
0
i want know how do it ? is it possible write it to file and i look at it later ?
0
Can do the following command in Python

 awk '{print $1,$2}' | cut -f1 -d'.' " "| sed '1d' | sed /^-/d | sed '/_/!d' | sed 's/ /:/g' | uniq
0
Hi
Installing Pycharm w/ a Youtube vid suggests I'll need 3.6.2 interpreter. I couldn't find an automatic update in the sections.

Is that necessary? It seems to be so. in the vid   ( here )

In preferences, there is no Pygame in the easy install type list - should it be there?
Thanks
0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.