Categories > Coding > Python >

What is the output of the given Python code

Posts: 13

Threads: 8

Joined: Mar, 2023

Reputation: 0

Posted

I've done coding for a few months and have reached a plateau. The code below just produces a menu and executes a few shell commands, which are then shown on the screen.

 

Here is the code:

#Imports
import os
import subprocess


#Set Globals for Workspace to 0
workspace = 0
absolute_path = 0


#Initally clear the screen
os.system('clear')

#Define Option 0 - Create a Workspace
def workspace_menu():
    print ("Enter the name of the Workspace or type 'q' or 'quit' to return to the main menu")
    print ("")
    workspace_input = input(":")
    if workspace_input in ("q", "quit"):
        os.system('clear')
    else:
#Define the current working directoy (__file__)
    script_dir = os.path.dirname(__file__)
    relative_path = 'workspaces/'
    joined_path = os.path.join(script_dir, relative_path)
    os.chdir(joined_path)
    if os.path.exists(workspace_input):
        print ("Directory already Exists! - Try a different name")
        input("Press any key to Return to the Main Menu")
        os.system('clear')
    else:
        make_path = os.makedirs(workspace_input)
        absolute_path = joined_path + workspace_input
        global absolute_path
        absolute_path = absolute_path
        global workspace
        workspace = 1
        print ("Workspace created!"), absolute_path
        input("Press any Key to Continue")
        os.system('clear')
        return

#Define the Main Menu
def menu():
    print(" 0) Add a Workspace")
    print(" 1) System Tasks")
    print("11) Exit")


#Define System Tasks
def system_tasks():
    os.system('clear')
    print(" 1) Display Local Network information")
    print(" 5) Back")
    system_tasks_answer = int(input(":"))
    if system_tasks_answer == 1:
        print("The Local Network Configuration of this OS are:")
        print("")
        ifconfig = subprocess.call(['/sbin/ifconfig'])
        dns = subprocess.call(['cat', '/etc/resolv.conf'])
        print("")
        print(workspace)
        lni_menu = input("Press any Key to Continue")
        system_tasks()
        os.system('clear')
    elif system_tasks_answer == 5:
        os.system('clear')


loop=True

while loop:
    print (menu())
    mm_answer = int(input(":"))
    if mm_answer ==0:
        workspace_menu()
    elif mm_answer ==1:
        system_tasks()
    elif mm_answer ==11:
        break
    else:
        input("You did not give a valid answer, press any key to try again") 
        os.system('clear')

I'd want to transfer the result of menu 1 options to a "workspace." A workspace is a user-inputted directory in which when a shell command is performed, it saves the standard input as a file to the directory specified in this guide. I'll be running over 50 distinct commands at some point, and I'd like them all to be properly saved in their respective folders. Python 3.4 is currently in use.

 

So far, my code can ask for user input for a workspace, which results in the creation of a relative directory. What I need is for a file to be generated.

 

Any advice would be much appreciated.

  • 0

Thank you

Alternate

stop take my rice

vip

Posts: 712

Threads: 113

Joined: Mar, 2022

Reputation: 40

Replied

This code is extremely painful to look at, but, here's how to write to a file in Python:

# Opens a file for writing, if the file does not exist yet it will create it
file = open(f"{directory}/file.txt", "w")
# Writes to the file
file.write("This will write content to a specific file in a specific directory. The file extension (.txt) can be changed to a different file extension if needed.")

# When done close the file
file.close()
  • 1

we are dead

Posts: 1

Threads: 0

Joined: Mar, 2023

Reputation: 0

Replied

 I also face some proble with the output of Python to code for shell shockers. There are some bugs in running process but I cannot find them. It's so great if there is anyone can help me to find or have any recommendation for bugfixes.

  • 0

VisualPlugin

VisualPlugn't

Posts: 111

Threads: 25

Joined: Nov, 2021

Reputation: 9

Replied

@Alternate: the 'with' clause is preferred.

with open(f"{directory}/file.txt", "w") as file:
  file.write("This will write content to a specific file in a specific directory. The file extension (.txt) can be changed to a different file extension if needed.")
  • 0

Your SUPREME RESPECTED LEADER VISUALPLUGIN blesses the current occasion which attracts you to my presence.

Murz

PixelPenguin

Posts: 240

Threads: 20

Joined: Jul, 2021

Reputation: 29

Replied

I did not really look through this much as I got bored.

 

I want to point a little something I noticed out really quickly though. I noticed that there were 3 lines at the start that could be turned into 1.

 

print ("Enter the name of the Workspace or type 'q' or 'quit' to return to the main menu")
print ("")
workspace_input = input(":")

 

You have two prints and one input. If I do not mistake input also prints the console if given actual parameters, maybe instead of adding the random prints try something like this:

 

workspace_input = input("Enter the name of the Workspace or type 'q' or 'quit' to return to the main menu: ")

 

Once again I don't really mess with python that much so I do not know what is considered good or bad practices.

 

Hopefully you or I will learn something from this reply!

  • 1

 

Ty for rep: Swiney, Byoke, Lion, Locust, Waves, Weeb, Nickk, darkn, Atari, CubeFaces, Lux14, Rice, Delta, Syraxes, Aeon, Jordan, Pluto, and Hiroku!

P.S, I like cats better too!

zenkai

zenkai

Posts: 5

Threads: 0

Joined: Apr, 2023

Reputation: 0

Replied

You can modify your code as follows:

  1. In the system_tasks() function, after performing a shell command and obtaining the standard output, you can prompt the user to enter a filename for the output file.

  2. Create a function, let's call it save_output(), which takes the output string and the workspace directory path as parameters. In this function, you can create a file with the specified filename inside the workspace directory and write the output string to that file.

  3. Call the save_output() function with the output string and the workspace directory path.

  4. In the modified code, the save_output() function takes the output string, the workspace directory path (absolute_path), and a filename as parameters. It combines the workspace directory path and the filename to create the full file path. Then, it opens the file in write mode and writes the output string to the file.

    You can modify the save_output() function according to your requirements, such as adding error handling or customizing the file-saving process.

    Remember to adapt this example to the rest of your code and ensure that the appropriate variables and functions are called in the right places.

(I can't provide the code here since it'd mess up the whole game)

  • 0

https://cdn.discordapp.com/attachments/1113823000429600880/1114600004032663552/User.gif?width=1000&height=100

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )