open games on ubuntu from python script - python

i am building a python script that can do certain tasks. I am now focusing on opening and application from the script i used subprocess.call and os.startfile but nothing helped and returned error the code is-
import os
while True:
message=raw_input("Enter your message >> ")
if message=="quit":
exit()
elif message=="bye":
exit()
elif message=="bye bye":
exit()
elif message=="good bye":
exit()
elif message=="see u":
print "Okay then :)"
exit()
elif message=="open games":
print "on to that"
os.start(gnome-mines)
Any help is appreciated

os.startfile is only available with Windows.
Please check here !!!
Instead of os.startfile, use os.system.
Make sure file and user has execution permissions.

you have to enter the complete path of the file to be opened
elif message=="open games":
print "on to that"
os.system("/usr/games/gnome-mines")

Related

Why am I getting an "No maching processes were found" error upon executing this python file?

I am working on a project in Python. Currently, only Option 1 works. (i just started this project) It goes through two levels of input and then runs a shell command that makes MacOS show a hidden file. But I am getting an error in the Macos Terminal upon running it: "No matching processes were found." Do you have any idea on why it could be doing this?
My code is too large to fit here, so here is a pastebin link: https://pastebin.com/EuBJjge6
#!/usr/bin/env python
import os
#function by popcnt on stackoverflow
def clear():
os.system('cls' if os.name =='nt' else 'clear')
# thanks to No Spoko on StackOverflow for the original idea, what you see here is modified
def printLogo():
f = open('logo.txt', 'r')
logo = f.read()
print(logo)
f.close()
clear()
printLogo()
print('Welcome to Belowdeck! \n')
#some code ideas from stackoverflow, don't remember the user
menuItem = {}
menuItem['1']="Show hidden files and folders"
menuItem['2']="Hide a file or folder from view"
menuItem['3']="Download files without a web browser"
menuItem['4']="List contents of a folder"
menuItem['5']="View any file's contents"
menuItem['6']="Change permissions of a file"
menuItem['7']="Restore a disk image to a device connected to your Mac"
menuItem['8']="Change the default screenshot location"
menuItem['9']="Change the default screenshot format"
menuItem['10']="Stop apps from syncing to iCloud by default"
menuItem['11']="Check for macOS updates every day instead of every month"
menuItem['12']="Enable a sound when your Mac connects to a power source"
menuItem['13']="Make holding down a key repeat characters"
menuItem['14']="Dull hidden apps in your Dock"
menuItem['15']="Hide non-active apps in your Dock"
menuItem['16']="Add a spacer to your Dock"
menuItem['17']="Change the delay before your Dock slides out"
menuItem['18']="Change the speed at which your Dock slides out"
menuItem['19']="Disable auto-restore in the Preview app"
menuItem['20']="Add a message to the login window"
menuItem['21']="Get rid of Dashboard"
menuItem['22']="Rebuild Spotlight"
menuItem['23']="Destroy your Mac \n"
options=menuItem.keys()
sorted(options)
for entry in options:
print (entry, menuItem[entry])
def option1():
clear()
print("Show hidden files and folders \n")
selection1=input("Would you like to proceed with the operation? (y/n): ")
if selection1 == "y" or selection1 == "Y":
os.system("defaults write com.apple.finder AppleShowAllFiles -bool TRUE && killall finder")
else:
input('Invalid selection! ')
while True:
menuSelection=input("Please select your desired action:")
if menuSelection =='1':
option1()
elif menuSelection == '2':
print ("delete")
elif menuSelection == '3':
print ("find")
elif menuSelection == '4':
print ('4')
else:
print ("Invalid action!")
I don't have access to a Mac, but Googling that error message throws up a lot of hits where people have had issues trying to kill processes. It's very likely that the issue is in line 59. Make sure the commands are correct. Also, avoid using os.system() call to execute shell commands -- it is not recommended. Use the subprocess module instead.
https://docs.python.org/3/library/subprocess.html#subprocess-replacements
https://www.youtube.com/watch?v=oQxTSDh-ECk

Having a file pathname as a starting input of a Python program

Just for fun, I tried to make a shortcut for the "java -jar filepathname" command on the Windows prompt.
import os
import time
def getJarFileName(pathName):
jarFileName = ""
for i in range(0, len(pathName)):
if (pathName[i] == "\\"):
jarFileName = ""
else:
jarFileName += pathName[i]
return jarFileName
jarFound = False
while (jarFound == False):
jarPathName = input("Insert a *.jar file pathname to execute:\n")
if not (jarPathName.endswith(".jar")):
jarPathName += ".jar"
if (os.access(jarPathName, os.R_OK)):
os.system('cls')
os.system("java -jar " + jarPathName)
jarFound = True
print("\n| \"%s\" terminated. |" % getJarFileName(jarPathName))
time.sleep(1)
else:
print("\n| \"%s\" not found. |\n" % getJarFileName(jarPathName))
This works wonderfully, but I'd like to skip the input process, and basically be able to directly open .jar files with this program (maybe by dropping jar files on this launcher's icon, and stuff like that). I searched all evening for something like this, but I couldn't find anything. Is what I want to do even possible? Thanks in advance for your help.
NB: I know that there are other more convenient ways to open .jar files, I'm just playing around with this kinds of things.

Making a GUI File Downloader with Python 3 and Tkinter

(I am using python 3.6.6 if that matters to anyone)
I am making a GUI installer for a game that is currently in private alpha and is constantly updating.
I already made a console version:
from tqdm import tqdm
import requests, os, sys, zipfile, shutil, subprocess
chunk_size = 1024
url = "{LINK TO FILE YOU WANT TO DOWNLOAD}"
r = requests.get(url, stream = True)
total_size = int(r.headers['content-length'])
print("Are you sure you want to download the newest version of RFMP?")
print("y/n", end=': ')
answer = input()
while True:
if answer == 'y':
if os.path.exists("RFMB6_WINDOWS"):
print('')
print('')
print('Removing old RFMP files...')
subprocess.check_call(('attrib -R ' + 'RFMB6_WINDOWS' + '\\* /S').split())
shutil.rmtree('RFMB6_WINDOWS')
print('')
print('Removed old files.')
break
else:
break
elif answer == 'n':
sys.exit()
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
print('')
print('')
print('Downloading:')
with open('RFMB6_WINDOWS.zip', 'wb') as f:
for data in tqdm(iterable = r.iter_content(chunk_size = chunk_size), total = total_size/chunk_size, unit = 'KB'):
f.write(data)
print('')
print("Download Complete.")
print('')
print('')
print("Would you like to extract it?")
print("y/n", end=': ')
answer2 = input()
while True:
if answer2 == 'y':
print('')
print('')
print('Extracting...')
zip_ref = zipfile.ZipFile("RFMB6_WINDOWS.zip", 'r')
zip_ref.extractall("RFMB6_WINDOWS")
zip_ref.close()
print('')
print('Extraction Complete')
print('')
print('')
print('Cleaning up...')
os.remove("RFMB6_WINDOWS.zip")
print('')
print('Done! You have succesfully installed the newest version of the Ravenfield Multiplayer Private Alpha.')
break
elif answer2 == 'n':
print('')
print('Done! You have succesfully downloaded the newest Zip of the Ravenfield Multiplayer Private Alpha.')
break
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
os.system('pause')
I will only be using this to download 1 specific link so ignore the url variable.
I am trying to make a GUI that does the same thing when I click a button that says 'Download'. I want to make a progress bar, and a text box that tells you what is going on e.g. Downloading, extracting etc. I have no need for a directory option. I just need it to download where ever the file is located and delete the old file if it is still there.
So here is my question: How do I learn how to do this? I have looked at tkinter tutorials and other questions but I only find stuff for python 2 or stuff that is to developed to modify and call my own work. What I am looking for are links and/or examples that can tell me how I go about creating something like this. Thanks in advance to anyone who helps me out.
P.S. I am a noob when it comes to coding so whatever you explain please do it thoroughly.
P.S.S. In order to run the console application you need to run it through terminal and add your own link in the 'url' variable.
Take a look at PySimpleGUI. You can build a layout with a download button, an output window and a progress bar easily. Stop by the GitHub and post an issue if you run into trouble.
The documentation for Tkinter with Python3:
https://docs.python.org/3/library/tk.html
This answer might help you out:
How to create downloading progress bar in ttk?
documentation: https://tkdocs.com/tutorial/morewidgets.html#progressbar

sys.exit in python console

Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:
if name == "lin":
do stuff
elif name == "static":
do other stuff
else:
sys.exit("error in input argument name, Unknown name")
If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.
I use Python 2.7 with Spyder on MAC.
Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?
Thanks for help
Not sure this is what you should be using sys.exit for. This function basically just throws a special exception (SystemExit) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit. It displays the message and then goes back to the REPL.
Rather than using sys.exit you should do something like:
def do_something(name):
if name == "lin":
print("do stuff")
elif name == "static":
print("do other stuff")
else:
raise ValueError("Unknown name: {}".format(name))
while True:
name = raw_input("enter a name: ")
try:
do_something(name)
except ValueError as e:
print("There was a problem with your input.")
print(e)
else:
print("success")
break # exit loop
You need to import sys. The following works for me:
import sys
name="dave"
if name == "lin":
print "do stuff"
elif name == "static":
print "do other stuff"
else:
sys.exit("error in input argument name, Unknown name")

Reading a character in python using readchar package

I'm trying to read a character in python so that to perform an action based on the input. I understood there is no easy way to read key strokes in python with the help of Google. I finally found 'readchar' package which is promising but I was not able to make it work in a simple program. Any help is greatly appreciated.
import readchar
def keyprint():
while True:
print "Press 'A' to Start the recording"
print " 'Z' to Stop the recording"
print " 'Enter' to quit the program..."
# Read a key
key = readchar.readkey()
if(key == 'A'):
print "Started Recording..."
elif(key == 'Z'):
print "Stopped Recording..."
elif(key == '\r'):
print "Exiting..."
break
else:
print "Please Use only allowed keys: A, Z, Enter!"
if __name__ == "__main__":
keyprint()
EDIT: Output Error
File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 22, in <module>
keyprint()
File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 10, in keyprint
key = readchar.readkey()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar.py", line 20, in readkey
c1 = getchar()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar_linux.py", line 12, in readchar
old_settings = termios.tcgetattr(fd)
termios.error: (25, 'Inappropriate ioctl for device')
Thanks,
inblueswithu
After discussing this issue on github with the creator of the project - magmax (here), I understood that readchar package works only if you try to run it from a terminal but not from any IDE or other non terminal executions. The error is caused because it tries to get the terminal settings which is non existent in this case.
I have been trying to run it from an Wing IDE. The program works great if you try to run it from a terminal.
P.S: magmax suggested to use readchar.keys.ENTER instead of \r . And suggested to have a look at https://github.com/magmax/python-inquirer & its examples

Categories

Resources