Python os.system(python "program") not working - python

I'm writing a program with multiple pieces of code, and don't want someone to have to manually copy-paste the entire directory from an install disk, so I've written something that will do it for them (like an autorun).
However, when I try to launch the program after copying it over to the user's computer, I get:
Process finished with exit code 0
instead of the installer booting the program.
This is the def I'm using:
import os
get_project_base_directory()
check_version()
print jason_dir
new_dir = str(jason_dir+"/Jason_Core/Boot.py")
command = "python " + new_dir
print command
os.system(command)
Why might os.system might not be working? I've also tried popopen and subprocess, but the had the same output (exit code 0).
EDIT: I am running this in a script, not the python command line.
EDIT 2: As requested, Boot.py:
# 3rd party libraries
import os
import subprocess
import shutil
from imp import find_module
# My code to import
basedir = ""
# Get the project base directory (drive located on)
def get_project_base_directory():
global basedir
cwd = os.getcwd()
basedir = "/".join(cwd.split("\\")[:len(cwd.split("\\"))-1])
#print basedir
# Copies libraries from disk drive
def copy_libs():
new_dir = "c:/Downloads/Python_Libraries"
if os.path.exists(new_dir):
shutil.rmtree(new_dir)
old_dir = basedir + "/Libraries/Installed"
#print old_dir
try:
shutil.copytree(old_dir, new_dir)
except:
print " Error copying directories! Try manual copy."
print " Go to:", basedir + "/Libraries/Installed"
# Checks to see if the library is installed
def check_lib_install():
temp_var = True
libs_list = ("fbchat", "gtts", "pyaudio", "googlevoice", "espeak", "pywapi", "speech_recognition", "win10toast") # names of libs
for lib in libs_list:
print "Checking lib installation:", lib
try:
__import__(lib)
print " Lib installed"
print ""
except:
print " Lib not installed"
install_lib(lib, libs_list.index(lib))
print "All libraires installed!"
# Install libraries if they don't exist on this machine.
def install_lib(lib, index):
print " Installing lib:", lib
libs_file_list = ("/fbchat-1.0.19/", "/gTTS-1.2.2/", "/PyAudio-0.2.11/", "/pygooglevoice-master/", "/python-espeak-0.5/", "/pywapi-0.3.8/", "/speech_recognition-master/", "/Windows-10-Toast-Notifications-master/") # path to file
print "Installing:", lib
new_dir = "c:/Downloads/Python_Libraries" + libs_file_list[index]
os.chdir(new_dir)
try:
temp_command = "python setup.py install"
subprocess.call(temp_command)
except:
print lib, "failed installation. Try manual install."
print ""
# Gets version number of local copy of Jason, and then the version number of the one on the disk drive. If the local version is lower, the python files are overwritten. If it doesn't yet exist locally, Jason is installed.
def check_version():
local_version = "0"
jason_dir = "C:/Jason_AI" # Where is jason installed to?
if os.path.exists(jason_dir):
with open(jason_dir+"\System Files\Version Number.txt") as local_jason: # Where is jason installed to?
counter = 0
for line in local_jason:
counter += 1
if counter == 2:
local_version = line
#print local_version
elif counter == 3:
break
install_version_file = basedir + "\System Files\Version Number.txt"
install_version_file = "/".join(install_version_file.split("\\"))
with open(install_version_file) as drive_jason:
counter = 0
for line in drive_jason:
counter += 1
if counter == 2:
install_version = line
#print install_version
if install_version == local_version:
print "Version up to date!"
print "Using version number:", local_version
else:
shutil.rmtree(jason_dir)
print "Version outdated"
print "Using version number:", local_version
elif counter == 3:
break
else:
print "Version outdated"
print "Using version number:", local_version
# Controls the boot process, when done, launches into Listen.get_audio()
def control():
get_project_base_directory()
copy_libs()
check_lib_install()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
check_version()
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
def check_packages():
packages = ["System_Logins", "Actions", "System_Commands", "Listen"]
for package in packages:
try:
__import__(package) #Need to work on
print package + ":", "successfully loaded."
packages[packages.index(package)] = "True"
except ImportError:
print package + ":", "error."
return packages
#Remote login (ie, from install)
def remote_control():
packages = check_packages()
#print packages
if any(word in ("System_Logins", "Actions", "System_Commands", "Listen") for word in packages):
control()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
remote_control()

Related

Getting software installation path through winreg

I'm trying to get the installation dir of every application installed in my system , then I will store those dir in notepad or anywhere then access that. so basically I want to build a python app like cortana which open any application installed in my system and open it. so this what I thought of
get path of installation from reg with help of winreg
then store it
then access it with other py program that take input of application name and search in that file copy the whole path of that specific application then send it to a python file which has os.open and application start .
and i will store data in sqllite3 or txt file .
the below code doesnt display anything
import winreg
def app(hive, flag):
areg=winreg.ConnectRegistry(None,hive)
akey=winreg.OpenKey(areg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
0, winreg.KEY_READ | flag)
subkey=winreg.QueryInfoKey(akey)[0]
soft_list=[]
for i in range(subkey):
soft={}
try:
soft['path']=winreg.QueryValueEx(subkey, "InstallSource")[0]
except:
soft['path']="null"
soft_list.append(soft)
return soft_list
soft_list = app(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY) + app(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY) + app(winreg.HKEY_CURRENT_USER, 0)
for software in soft_list:
print (software['path'])
print(len(soft_list))
this below code works idk y but it dont display all application
import winreg
def foo(hive, flag):
aReg = winreg.ConnectRegistry(None, hive)
aKey = winreg.OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
0, winreg.KEY_READ | flag)
count_subkey = winreg.QueryInfoKey(aKey)[0]
software_list = []
for i in range(count_subkey):
software = {}
try:
asubkey_name = winreg.EnumKey(aKey, i)
asubkey = winreg.OpenKey(aKey, asubkey_name)
software['name'] = winreg.QueryValueEx(asubkey, "DisplayName")[0]
try:
software['i']=winreg.QueryValueEx(asubkey,"InstallSource")[0]
except EnvironmentError:
software['i'] = winreg.QueryValueEx(asubkey, "InstallSource")[0]
software_list.append(software)
except EnvironmentError:
continue
return software_list
software_list = foo(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY) + foo(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY) + foo(winreg.HKEY_CURRENT_USER, 0)
for software in software_list:
print (software['name'], software['i'])
print('Number of installed apps: %s' % len(software_list))
and this code below display all application(352 app) but when i add for path the code dont display all application(205)
import winreg
def foo(hive, flag):
aReg = winreg.ConnectRegistry(None, hive)
aKey = winreg.OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
0, winreg.KEY_READ | flag)
count_subkey = winreg.QueryInfoKey(aKey)[0]
software_list = []
for i in range(count_subkey):
software = {}
try:
asubkey_name = winreg.EnumKey(aKey, i)
asubkey = winreg.OpenKey(aKey, asubkey_name)
software['name'] = winreg.QueryValueEx(asubkey, "DisplayName")[0]
software_list.append(software)
except EnvironmentError:
continue
return software_list
software_list = foo(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY) + foo(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY) + foo(winreg.HKEY_CURRENT_USER,0)
for software in software_list:
print (software['name'])
print('Number of installed apps: %s' % len(software_list))
There's no good answer for your question.
You won't find all install paths from registry.
Also, InstallSource would not be the installed path, but it's source, and is often missing.
Btw, I wrote a package that does what you coded above, called windows_tools.installed_software
from windows_tools.installed_software import get_installed_software
for software in get_installed_software():
print(software['name'], software['version'], software['publisher'])
From my experience, there's no good way to list all installed programs under windows.
You might need to combine various sources, like WMI, registry and perhaps walking over program filesand program files (x86)
One way to get the data via WMI:
from windows_tools.wmi_queries import query_qmi
product = query_wmi('SELECT * FROM Win32_Product', 'cimv2', 'test_query', can_be_skipped=False)
for product in products:
print(product)
Good luck.
Since anshul raj asked for a way to get all executable files in order to find which programs are installed, here's a solution for that problem.
Still, this will only list all executable files in paths, and will produce a lot of results for existing programs that have more than one executable.
from ofunctions.file_utils import get_files_recursive
program_paths = [r'C:\Program Files', r'C:\Program Files (x86)']
executables = []
for program_path in program_paths:
executables += get_files_recursive(program_path, ext_include_list=['.exe'])
print(executables)
Disclaimer: I'm the author of ofunctions module

ModuleNotFoundError: No module named 'pyzabbix'

pyzabbix is a module needed for this script to work. I installed it using pip, please see a confirmation below:
WARNING: The script chardetect.exe is installed in 'C:\Users\Christopher Ezimoha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2019.11.28 chardet-3.0.4 idna-2.8 pyzabbix-0.7.5 requests-2.22.0 urllib3-1.25.8
C:\Users\Christopher Ezimoha\Desktop>
However, I'm getting an error at line 24 that the module can't be found. I'm not sure what I need to do.
Please see the script below and advise accordingly as I need this code to read a CSV file and update an application called Zabbix.
def addHosts(zapi):
# Add Hosts
file = open('hosts.csv', 'r')
reader = csv.reader(file)
devicelist = list(reader)
import csv
def login():
# Login/authenticate below
session = ZabbixAPI('https://zabbix.xxxxxx.xxx')
# session = ZabbixAPI('http://xxxxxxxxxx/zabbix')
session.login(user="xxxxxxxxxxxx", password="xxxxxxxx")
print("Connected to Zabbix API Version %s" % session.api_version())
return session
for row in devicelist:
device = row[0]
hostgroup = row[1]
responsegroup = zapi.hostgroup.get(filter={'name': hostgroup})
groupid = responsegroup[0]['groupid']
ip = row[2]
templatePriority = row[3]
responsepriority = zapi.template.get(filter={'name': templatePriority})
templatePriorityId = responsepriority[0]['templateid']
# if templatePriority == 'P1':
# templatePriorityId = '40874'
templateType = row[4]
responsetype = zapi.template.get(filter={'name': templateType})
templateTypeId = responsetype[0]['templateid']
try:
response = zapi.host.create(
host=device,
interfaces=[{
'type': 2,
'main': 1,
'ip': ip,
'dns': '',
'port': 161,
'useip': 1
}],
groups=[{
'groupid': groupid}],
templates=[{'templateid': templatePriorityId}, {'templateid': templateTypeId}],
inventory_mode=1
)
print("Created new host: " + device)
except ZabbixAPIException as e:
if 'already exists' in e[0]:
print("Already created host " + device)
else:
print(e[0])
return
def main():
# hostgroup = raw_input('Hostgroup: ')
#hostgroup = "ALTC - Altcar"
zapi = login()
addHosts(zapi)
return
if __name__ == '__main__':
main()
Do you have both python 2 and 3 installed? If you have both, pip installs modules under python2. Try installing like this if you'd like the module to be installed under python3:
pip3 install pyzabbix
There is no import, in the code you included in the question:
from pyzabbix import ZabbixAPI
The login() function should be defined outside of addHosts(), in order to be called like that in main()

How to get a git diff so I can use it to bump my version with semver? (ThreeDotLabs Tutorial)

I have used the Tutorial from ThreeDotsLab to create my automated versioning for my CI/CD pipeline in git (the pipeline builds debian packages and delivers them to my server).
I have already tried various answers from posts like this question.
Maybe I am just too stupid to get this right but this is what my code looks like right now:
#!/usr/bin/env python3
#automatic versioning like explained in https://threedots.tech/post/automatic-semantic-versioning-in-gitlab-ci/
import os
import re
import sys
import semver
import subprocess
def git(*args):
return subprocess.check_output(["git"] + list(args))
def tag_repo(tag):
url = os.environ["CI_REPOSITORY_URL"]
# Transforms the repository URL to the SSH URL
# Example input: https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx#gitlab.com/threedotslabs/ci-examples.git
# Example output: git#gitlab.com:threedotslabs/ci-examples.git
push_url = re.sub(r'.+#([^/]+)/', r'git#\1:', url)
git("remote", "set-url", "--push", "origin", push_url)
git("tag", tag)
git("push", "origin", tag)
def bump(latest):
# refer to: https://stackoverflow.com/questions/22021825/how-to-do-a-git-diff-of-current-commit-with-last-commit-using-gitpython
content = repo.index.diff(repo.commit('HEAD~1'), create_patch=True)
if "app.py" in content:
return semver.bump_major(latest)
#on logical changes in application increase version-majornumber example: increase 1.0.0 to 2.0.0
elif "templates/" in content:
return semver.bump_minor(latest)
#on html-template changes increase version-minornumber example: increase 1.0.0 to 1.1.0
elif "static/scripts" in content:
return semver.bump_minor(latest)
#on script changes increase version-minornumber example: increase 1.0.0 to 1.1.0
elif "static/styles/" in content:
return semver.bump_patch(latest)
#on css changes increase version-patchnumber example: increase 1.0.0 to 1.0.1
elif "static/img/" in content:
return semver.bump_patch(latest)
#on img changes increase version-patchnumber example: increase 1.0.0 to 1.0.1
elif ".git" in content:
return latest
#Do not increase version on git conf changes
elif "deb-pkg-data/" in content:
return latest
#Do not increase version on packaging script changes
else:
return semver.bump_patch(latest)
#Default: increase version-patchnumber example: increase 1.0.0 to 1.0.1
def main():
try:
latest = git("describe", "--tags").decode().strip()
except subprocess.CalledProcessError:
# No tags in the repository
version = "1.0.0"
else:
# Skip already tagged commits
if '-' not in latest:
print(latest)
return 0
version = bump(latest)
if version == latest:
return 0
tag_repo(version)
print(version)
return 0
if __name__ == "__main__":
sys.exit(main())
The script generally works. The only thing that does not is my part with the if and elif. Generally I want to get a git diff --name-only to pass to my conditionals. If there is a change in app.py I always want to bump my major version.
EDIT:
I have tried the following and I am getting the following error: subprocess.CalledProcessError: Command '['git', 'diff', '--name-only', '>', 'patchedfiles.txt']' returned non-zero exit status 128.
My improved code:
git("diff", "--name-only", ">", "patchedfiles.txt")
patchedFiles = open("patchedfiles.txt", "r")
content = patchedFiles.read()
if "app.py" in content:
patchedFiles.close()
os.remove("patchedfiles.txt")
return semver.bump_major(latest)
#on logical changes in application increase version-majornumber example: increase 1.0.0 to 2.0.0
I did solve it with the help of a colleague.
We made a different approach - we tried to analyze the commit message in git for certain keywords.
If anyone wants to know the answer to my problem - here it is:
#!/usr/bin/env python3
import os
import re
import sys
import semver
import subprocess
def git(*args):
return subprocess.check_output(["git"] + list(args))
def tag_repo(tag):
url = os.environ["CI_REPOSITORY_URL"]
# Transforms the repository URL to the SSH URL
# Example input: https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx#gitlab.com/threedotslabs/ci-examples.git
# Example output: git#gitlab.com:threedotslabs/ci-examples.git
push_url = re.sub(r'.+#([^/]+)/', r'git#\1:', url)
git("remote", "set-url", "--push", "origin", push_url)
git("tag", tag)
git("push", "origin", tag)
def bump(latest):
MyOutput = subprocess.Popen(['git', 'log', '--format=%B', '-n', '1', 'HEAD'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr = MyOutput.communicate()
if stderr != None:
return latest
else:
commitMSG = stdout.decode("utf8")
try:
words = commitMSG.lower()
if "major" in words:
return semver.bump_major(latest)
elif "minor" in words:
return semver.bump_minor(latest)
elif "patch" in words:
return semver.bump_patch(latest)
else:
return latest # return latest already existing version if no keyword is used in the commit message
except:
print("encountered non-char object in commit msg - moving on")
def main():
try:
latest = git("describe", "--tags").decode().strip()
except subprocess.CalledProcessError:
# No tags in the repository
version = "1.0.0"
else:
# Skip already tagged commits
if '-' not in latest:
print(latest)
return 0
version = bump(latest)
if version == latest:
return 0
tag_repo(version)
print(version)
return 0
if __name__ == "__main__":
sys.exit(main())

How to extract Deployed OSB Source code from Environment or SB Console or Weblogic

Could anyone please help me in getting a way to get the source code from Environment or SB Console or Weblogic.
I created the python script whick exports the JAR, but I need the source code. Because if I unjar the jar, I do not get the exact source code, as file names are shorten and some code is added by itself in wsdls, xqueries etc. I don't want that.
Here's my wlst Python/Jython Script:
from java.io import FileInputStream
from java.io import FileOutputStream
from java.util import ArrayList
from java.util import Collections
from com.bea.wli.sb.util import EnvValueTypes
from com.bea.wli.config.env import EnvValueQuery;
from com.bea.wli.config import Ref
from com.bea.wli.config.customization import Customization
from com.bea.wli.config.customization import FindAndReplaceCustomization
import sys
#=======================================================================================
# Utility function to load properties from a config file
#=======================================================================================
def exportAll(exportConfigFile):
def exportAll(exportConfigFile):
try:
print "Loading export config from :", exportConfigFile
exportConfigProp = loadProps(exportConfigFile)
adminUrl = exportConfigProp.get("adminUrl")
exportUser = exportConfigProp.get("exportUser")
exportPasswd = exportConfigProp.get("exportPassword")
exportJar = exportConfigProp.get("exportJar")
customFile = exportConfigProp.get("customizationFile")
passphrase = exportConfigProp.get("passphrase")
project = sys.argv[2]
if project == None :
project = exportConfigProp.get("project")
connectToServer(exportUser, exportPasswd, adminUrl)
ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
print "ALSBConfiguration MBean found"
print "Input project: ", project
if project == None :
ref = Ref.DOMAIN
collection = Collections.singleton(ref)
if passphrase == None :
print "Export the config"
theBytes = ALSBConfigurationMBean.exportProjects(collection, None)
else :
print "Export and encrypt the config"
theBytes = ALSBConfigurationMBean.export(collection, true, passphrase)
else :
ref = Ref.makeProjectRef(project);
print "Export the project", project
collection = Collections.singleton(ref)
theBytes = ALSBConfigurationMBean.export(collection, false, None)
aFile = File(exportJar)
out = FileOutputStream(aFile)
out.write(theBytes)
out.close()
print "ALSB Configuration file: "+ exportJar + " has been exported"
if customFile != None:
print collection
query = EnvValueQuery(None, Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false)
customEnv = FindAndReplaceCustomization('Set the right Work Manager', query, 'Production System Work Manager')
print 'EnvValueCustomization created'
customList = ArrayList()
customList.add(customEnv)
print customList
aFile = File(customFile)
out = FileOutputStream(aFile)
Customization.toXML(customList, out)
out.close()
print "ALSB Dummy Customization file: "+ customFile + " has been created"
except:
raise
#=======================================================================================
# Utility function to load properties from a config file
#=======================================================================================
def loadProps(configPropFile):
propInputStream = FileInputStream(configPropFile)
configProps = Properties()
configProps.load(propInputStream)
return configProps
#=======================================================================================
# Connect to the Admin Server
#=======================================================================================
def connectToServer(username, password, url):
connect(username, password, url)
domainRuntime()
# EXPORT script init
try:
exportAll(sys.argv[1])
except:
print "Unexpected error: ", sys.exc_info()[0]
dumpStack()
raise
Any help would be appreciated.
What you get as a result of the export is the deployed unit. Yes, there is some metadata added/modified as a result of the deployment on the OSB runtime (deployment could also mean creating/editing components directly on the servicebus console).
To get it back as "source code" from the exported jar, you can simply import it back into JDeveloper (12c) or Eclipse with OEPE (11g)

import httplib ImportError: No module named httplib

I got this error when run test.py
C:\Python32>python.exe test.py
Traceback (most recent call last):
File "test.py", line 5, in <module>
import httplib
ImportError: No module named httplib
How to correct it?
Code block for test.py:
#!/usr/local/bin/python
import httplib
import sys
import re
from HTMLParser import HTMLParser
class miniHTMLParser( HTMLParser ):
viewedQueue = []
instQueue = []
def get_next_link( self ):
if self.instQueue == []:
return ''
else:
return self.instQueue.pop(0)
def gethtmlfile( self, site, page ):
try:
httpconn = httplib.HTTPConnection(site)
httpconn.request("GET", page)
resp = httpconn.getresponse()
resppage = resp.read()
except:
resppage = ""
return resppage
def handle_starttag( self, tag, attrs ):
if tag == 'a':
newstr = str(attrs[0][1])
if re.search('http', newstr) == None:
if re.search('mailto', newstr) == None:
if re.search('htm', newstr) != None:
if (newstr in self.viewedQueue) == False:
print (" adding", newstr)
self.instQueue.append( newstr )
self.viewedQueue.append( newstr )
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
def main():
if sys.argv[1] == '':
print ("usage is ./minispider.py site link")
sys.exit(2)
mySpider = miniHTMLParser()
link = sys.argv[2]
while link != '':
print ("\nChecking link ", link)
# Get the file from the site and link
retfile = mySpider.gethtmlfile( sys.argv[1], link )
# Feed the file into the HTML parser
mySpider.feed(retfile)
# Search the retfile here
# Get the next link in level traversal order
link = mySpider.get_next_link()
mySpider.close()
print ("\ndone\n")
if __name__ == "__main__":
main()
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.
You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.
you can just import http.client and rename it to httplib with this code :
import http.client as httplib
If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends flag:
apt-get install -y python

Categories

Resources