Joined for Python project

Joined
Dec 17, 2024
Messages
6
Reaction score
0
Just joined to sort out my Python project.
Question is :
AI and me, have tried to solve a range of errors: using PyCharm but I’m about to ditch it, lost a major part of my script, starting over once I get these interim intros out the way.

Basically, years ago excel VBA worked well and completed my then project, using Record Macro for Dynamic Web Query.
All good, until JSON came along and ruined everything. ( Bully JSON like one of those jerks who kick ya sandcastle at the beach).
Python seemed to be the solution, but long time ago, over 10 years.
I plan to “resurrect “ my project using Python as web query instrument.
Got it to ping ok the specific web site,
Then lost the lot when trying to sort out syntax errors and so forth.
Question is:
Is this the place to paste the Python code errors that an AI and myself just simply cannot sort out ?


Thanks
 
Joined
Dec 17, 2024
Messages
6
Reaction score
0
Ok,
here is my test ping code,
My errors are indentations, no matter what I try
either 4 or 8 indentations, I can't get this to work, each time
I Run the code; it keeps suggesting indentation errors.
Once this section of the code is corrected and actually creates
the log file, I hope to move on to the next section of the entire process.
Reason for the ping test and the variables,
A: To confirm it will query
B: to log a log in txt which I'm having trouble with the txt files further down the script.
C: why this web page ? Because it's something to identify with.

note: Run Error message is below the script

#Here's the Python code for the ping test:
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])

import requests



import os
import datetime
import time
import requests

# Adjustable variables
num_pings = 7
interval = 1 # seconds

# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"

# Log file settings
log_dir = "C:\\PingTestLogs"
log_file_name = "PingTestProjectA1.log"
max_log_size = 2048 # bytes (2 KB)

def ping_url(url):
try:
response = requests.head(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.RequestException:
return False

def log_ping_result(result):
log_file_path = os.path.join(log_dir, log_file_name)
current_time = datetime.datetime.now().strftime("%Y%m%d:%H:%M:%S")
log_entry = f"-:>{current_time}: {result}\n"

if not os.path.exists(log_dir):
os.makedirs(log_dir)

if os.path.exists(log_file_path):
log_file_size = os.path.getsize(log_file_path)
if log_file_size >= max_log_size:
os.remove(log_file_path)

with open(log_file_path, "a") as log_file:
log_file.write(log_entry)

def main():
for i in range(num_pings):
result = ping_url(url)
if result:
log_ping_result("Ping successful")
else:
log_ping_result("Ping failed")
time.sleep(interval)

if name == "main":
main()
#Here's the Python code for the ping test:
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])

import requests



import os
import datetime
import time
import requests

# Adjustable variables
num_pings = 7
interval = 1 # seconds

# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"

# Log file settings
log_dir = "C:\\PingTestLogs"
log_file_name = "PingTestProjectA1.log"
max_log_size = 2048 # bytes (2 KB)

def ping_url(url):
try:
response = requests.head(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.RequestException:
return False

def log_ping_result(result):
log_file_path = os.path.join(log_dir, log_file_name)
current_time = datetime.datetime.now().strftime("%Y%m%d:%H:%M:%S")
log_entry = f"-:>{current_time}: {result}\n"

if not os.path.exists(log_dir):
os.makedirs(log_dir)

if os.path.exists(log_file_path):
log_file_size = os.path.getsize(log_file_path)
if log_file_size >= max_log_size:
os.remove(log_file_path)

with open(log_file_path, "a") as log_file:
log_file.write(log_entry)

def main():
for i in range(num_pings):
result = ping_url(url)
if result:
log_ping_result("Ping successful")
else:
log_ping_result("Ping failed")
time.sleep(interval)

if name == "main":
main()


Run Error Message

File "C:\Users\LAPTOP\PyCharmMiscProject\script.py", line 55
result = ping_url(url)
^^^^^^
IndentationError: expected an indented block after 'for' statement on line 54

Process finished with exit code 1


Run Error Message:


File "C:\Users\LAPTOP\PyCharmMiscProject\script.py", line 55
result = ping_url(url)
^^^^^^
IndentationError: expected an indented block after 'for' statement on line 54

Process finished with exit code 1
 
Joined
Dec 17, 2024
Messages
6
Reaction score
0
Thanks,
I’m preparing the script /code
Keep watch
Sorry about the delay.
I need to uninstall PyCharm community edition. It’s getting too complicated to just create a new script project.
It goes nutz
Ok,
here is my test ping code,
My errors are indentations, no matter what I try
either 4 or 8 indentations, I can't get this to work, each time
I Run the code; it keeps suggesting indentation errors.
Once this section of the code is corrected and actually creates
the log file, I hope to move on to the next section of the entire process.
Reason for the ping test and the variables,
A: To confirm it will query
B: to log a log in txt which I'm having trouble with the txt files further down the script.
C: why this web page ? Because it's something to identify with.

note: Run Error message is below the script

#Here's the Python code for the ping test:
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])

import requests



import os
import datetime
import time
import requests

# Adjustable variables
num_pings = 7
interval = 1 # seconds

# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"

# Log file settings
log_dir = "C:\\PingTestLogs"
log_file_name = "PingTestProjectA1.log"
max_log_size = 2048 # bytes (2 KB)

def ping_url(url):
try:
response = requests.head(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.RequestException:
return False

def log_ping_result(result):
log_file_path = os.path.join(log_dir, log_file_name)
current_time = datetime.datetime.now().strftime("%Y%m%d:%H:%M:%S")
log_entry = f"-:>{current_time}: {result}\n"

if not os.path.exists(log_dir):
os.makedirs(log_dir)

if os.path.exists(log_file_path):
log_file_size = os.path.getsize(log_file_path)
if log_file_size >= max_log_size:
os.remove(log_file_path)

with open(log_file_path, "a") as log_file:
log_file.write(log_entry)

def main():
for i in range(num_pings):
result = ping_url(url)
if result:
log_ping_result("Ping successful")
else:
log_ping_result("Ping failed")
time.sleep(interval)

if name == "main":
main()
#Here's the Python code for the ping test:
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])

import requests



import os
import datetime
import time
import requests

# Adjustable variables
num_pings = 7
interval = 1 # seconds

# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"

# Log file settings
log_dir = "C:\\PingTestLogs"
log_file_name = "PingTestProjectA1.log"
max_log_size = 2048 # bytes (2 KB)

def ping_url(url):
try:
response = requests.head(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.RequestException:
return False

def log_ping_result(result):
log_file_path = os.path.join(log_dir, log_file_name)
current_time = datetime.datetime.now().strftime("%Y%m%d:%H:%M:%S")
log_entry = f"-:>{current_time}: {result}\n"

if not os.path.exists(log_dir):
os.makedirs(log_dir)

if os.path.exists(log_file_path):
log_file_size = os.path.getsize(log_file_path)
if log_file_size >= max_log_size:
os.remove(log_file_path)

with open(log_file_path, "a") as log_file:
log_file.write(log_entry)

def main():
for i in range(num_pings):
result = ping_url(url)
if result:
log_ping_result("Ping successful")
else:
log_ping_result("Ping failed")
time.sleep(interval)

if name == "main":
main()


Run Error Message

File "C:\Users\LAPTOP\PyCharmMiscProject\script.py", line 55
result = ping_url(url)
^^^^^^
IndentationError: expected an indented block after 'for' statement on line 54

Process finished with exit code 1


Run Error Message:


File "C:\Users\LAPTOP\PyCharmMiscProject\script.py", line 55
result = ping_url(url)
^^^^^^
IndentationError: expected an indented block after 'for' statement on line 54

Process finished with exit code 1
bump
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
First of all, never enter such code into the script,
Python:
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
because it is not recommended to include this kind of script in Python for the following reasons:
  1. Security Risks:
    • Automatically executing commands like pip install within a script can introduce vulnerabilities. For example, an attacker could exploit the script to install malicious packages.
    • Users might unintentionally execute harmful code, especially if the script is shared without proper scrutiny.
  2. Dependency Management:
    • Installing dependencies directly in the script does not give users control over their environment. Best practices involve specifying dependencies in a dedicated file, such as requirements.txt, and instructing users to install them using pip install -r requirements.txt.
    • This ensures the environment is predictable and consistent across different systems.
  3. Lack of Portability:
    • Running subprocess.check_call to install dependencies assumes that pip and internet access are available during execution, which might not always be the case.
    • Different systems may require custom configurations (e.g., virtual environments or system-specific permissions).
  4. Bad Practice for Reusability:
    • Scripts with built-in dependency installation make it harder to integrate the code into larger projects, where dependency management is often handled at the project level.
  5. Potential for Unexpected Behavior:
    • Automatically installing packages can interfere with existing environments or packages, causing conflicts or version mismatches.
Recommended approach:
Instead of embedding the dependency installation in a script, do something like the following:
  1. Create a requirements.txt file.
    Code:
    requests
  2. Instruct users to set up the environment.
    Code:
    pip install -r requirements.txt
  3. Include usage instructions in the documentation or comments within the script.
    Python:
    """
    This script requires the 'requests' library.
    Install it using: pip install -r requirements.txt
    """
    import requests

    IMO, this method is cleaner, safer, and aligns with Python development best practices.
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
C: why this web page ? Because it's something to identify with.
Python:
# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"
The URL "https://tab.com.au/racing/meetings/today/R" is not a suitable choice for testing with a ping command for the following reasons:
  1. Ping is Not Designed for URLs with Paths:
    The ping command works with domain names or IP addresses, not URLs that include paths (/racing/meetings/today/R). Using this URL will result in an error or undefined behavior.
  2. Potential Firewall or Blockage:
    Many websites, especially those handling sensitive data, may block ICMP (Internet Control Message Protocol) requests, which ping uses, for security reasons. This can make the test unreliable.
  3. Redirection and HTTPS:
    The URL is an HTTPS address, which is typically resolved to an IP address before a ping can occur. However, ping does not account for HTTPS-specific features like encryption or redirection, leading to incomplete testing.
  4. Specific Endpoint Unrelated to Network Reachability:
    The purpose of ping is to test basic network connectivity, not to validate the accessibility of a specific web endpoint or path. A better approach for testing a URL's accessibility is to use a tool like curl or a Python script with the requests library.
If testing basic network connectivity, use the base domain e.g. tab.com.au with ping in this case.

1734652714083.png


This is more like testing the accessibility of a specific URL, and instead of calling it ping, call it e.g. accessibility test or url test in this case.
Python:
import requests

url = "https://tab.com.au/racing/meetings/today/R"
try:
    response = requests.get(url)
    print(f"Status Code: {response.status_code}")
except requests.RequestException as e:
    print(f"Error: {e}")
 
Last edited:
Joined
Jul 4, 2023
Messages
545
Reaction score
71
Check this out (your code):
Python:
#Here's the Python code for the ping test:
import requests
import os
import datetime
import time

# Adjustable variables
num_pings = 7
interval = 1 # seconds

# URL to ping
url = "https://tab.com.au/racing/meetings/today/R"

# Log file settings
log_dir = "C:\\PingTestLogs"
log_file_name = "PingTestProjectA1.log"
max_log_size = 2048 # bytes (2 KB)

def ping_url(url):
    try:
        response = requests.head(url, timeout=5)
        if response.status_code == 200:
            return True
        else:
            return False
    except requests.RequestException:
        return False

def log_ping_result(result):
    log_file_path = os.path.join(log_dir, log_file_name)
    current_time = datetime.datetime.now().strftime("%Y%m%d:%H:%M:%S")
    log_entry = f"-:>{current_time}: {result}\n"

    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    if os.path.exists(log_file_path):
        log_file_size = os.path.getsize(log_file_path)
        if log_file_size >= max_log_size:
            os.remove(log_file_path)

    with open(log_file_path, "a") as log_file:
        log_file.write(log_entry)

def main():
    for i in range(num_pings):
        result = ping_url(url)

        if result:
            log_ping_result("Ping successful")
        else:
            log_ping_result("Ping failed")

        time.sleep(interval)

if __name__ == "__main__":
    main()
result = ping_url(url)
^^^^^^
IndentationError: expected an indented block after 'for' statement on line 54
Python:
def main():
    for i in range(num_pings):
        result = ping_url(url)
        
        if result:
            log_ping_result("Ping successful")
        else:
            log_ping_result("Ping failed")

        time.sleep(interval)
 
Last edited:
Joined
Dec 17, 2024
Messages
6
Reaction score
0
The “ why this page”

Well over 15 years ago, my entire project relied on VBA DYNAMIC WEB QUERY, using the exact same path, for the sole purpose to create the exact same meetings list in time order. (From am to pm). Daily.
Print the list, then I have a printed meetings list the way it ought to be, everything in dated time order.
VBA seems to have difficulties “communicating” with this JSON stuff when it came on board.
So my project got shelved. Till recently.
Using something as a simple “tailor made time order meeting list”, for educational and personal recreational purposes I learn coding. Python seems to be suitable for a “go-beween” vba web query and JSON.

So,
VBA triggers Python, Python gets meetings cos it’s “friendly” with JSON.
Python brings back to txt file.
Python then triggers VBA Macro.
VBA gets txt file.
Check weather reports if need be,
Recheck meetings, incase of “ meeting abandoned”,

Hopefully my dormant Excel workbook
does what it used to do.
And I continue self learning

Btw
VBService

"Thank you for the detailed explanation and guidance. Your advice is much appreciated, and I'll definitely keep these best practices in mind for future projects."
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
VBA seems to have difficulties “communicating” with this JSON stuff when it came on board.
Check this out:
VBA triggers Python, Python gets meetings cos it’s “friendly” with JSON.
Python brings back to txt file.
Python then triggers VBA Macro.
VBA gets txt file.
Check weather reports if need be,
Recheck meetings, incase of “ meeting abandoned”,
A clever approach to the problem, but it has such a complicated "scenario" unnecessarily, because you can now make all these assumptions using VBA, read below why I think so.

BTW,
When JSON first came onto the scene, it seemed like VBA struggled to "communicate" with it, making developers think twice about relying on this language.

I understand your concern about VBA struggling with JSON, especially when it first became popular. However, it's worth noting that VBA now has libraries and tools that make working with JSON much easier. Built-in support in newer Office versions allow you to parse and generate JSON fairly efficiently.

Given that VBA can still handle JSON and integrate with other tools effectively, perhaps it’s worth reconsidering its utility for certain tasks. If you’re already comfortable with VBA and it meets your needs, there’s no rush to move away from it entirely, especially for automating tasks in Office.

What do you think?
 
Last edited:
Joined
Dec 17, 2024
Messages
6
Reaction score
0
Check this out:

A clever approach to the problem, but it has such a complicated "scenario" unnecessarily, because you can now make all these assumptions using VBA, read below why I think so.

BTW,
When JSON first came onto the scene, it seemed like VBA struggled to "communicate" with it, making developers think twice about relying on this language.

I understand your concern about VBA struggling with JSON, especially when it first became popular. However, it's worth noting that VBA now has libraries and tools that make working with JSON much easier. Built-in support in newer Office versions allow you to parse and generate JSON fairly efficiently.

Given that VBA can still handle JSON and integrate with other tools effectively, perhaps it’s worth reconsidering its utility for certain tasks. If you’re already comfortable with VBA and it meets your needs, there’s no rush to move away from it entirely, especially for automating tasks in Office.

What do you think?
I’ll check it out, heard about the updates with excel json tools etc.
Version of my MS office is 2010
OS win 10
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,109
Messages
2,570,670
Members
47,260
Latest member
MadelaineK

Latest Threads

Top