I am beginner in python. I created project with three .py files and one database file in PyCharm. But don`t understand how run my project via cmd console or something else. Do I need to create start class like "main" or what to do? How can I sent my project to another people that they may run it?
On the screen I tried run .py file via cmd Windows console
Python program does not require "main function" as entry point, each line of a .py file will be executed sequentially. All you need is to type: python yourprogram.py in your console.
But on the other hand, many people choose to have a "main function" in their python program and only invoke this function when python program is run as a stand-alone script as opposed to being loaded as a module.
def main():
# do something
if __name__ == "__main__":
main()
Your code ran.
The error seems to suggest that it's running from the src folder and trying to open a src subdirectory with a database.
Without giving absolute paths, all file references are relative to the executed script. So, just connect to the database name, not src/Contacts.db
Each of your .py file is an executable. Depending on how you have coded, these files might be inter-dependent. In that case, there might be a main file(with any name, need not name it main.py, could be hello.py). So, you can run that file with python <filename>. As far as the language is concerned, there is no need to create a special class like main. Though you are free to do that.
General style it to include a statement in the end of the main file like suppose you have three files hello.py, bye.py, work.py, where
from work import *
from bye import *
def hello():
print "Hello"
if __name__ == "__main__":
hello()
You can run python hello.py
For sharing, you can create a zip of the folder and share that zip or you can create a git hub repository and share the github link.
The error is in opening the file. please check for spelling errors and the location of the db file
Related
Apologies if I am missing something obvious here. I have a PyQt5 app that I've frozen using the awesome fbs package. Within the app, a Python script is called via a PyQt subprocess, i.e. like this:
command = "python LaunchPPTKwin.py"
self.child = QProcess()
self.child.start("cmd.exe /C python LaunchPPTKwin.py")
self.child.waitForFinished(-1)
This works fine when the app is run on the machine on which the app was built. When I bring it to another machine, however, the app runs but the LaunchPPTKwin.py script is never executed. I assume this is because the other machine does not have python installed and/or does not have the LaunchPPTKwin.py script locally. My goal is to create an app so that this will work without the user needing to separately download python or the script, i.e. to make the app totally self contained. Is this possible using fbs?
P.S. Both machines are using Windows 10.
Either python is not installed or python is not in the search path and you had to locate it.
If python were installed, but not in the search path following code should work.
self.child.start("cmd.exe /C start LaunchPPTKwin.py")
If python is not installed at all you could cheat with more effort.
you had to make sure, that your frozen application can handle a command line parameter that allows it to start another script.
It would take the python file.
add the base directory of that file to sys.path strip of the .py suffix of the basename and import it and call it's main function. THis works however only if the script had following lines at its end
def main():
the_code_you_want_to_start
...
if __name__ == "__main__":
main()
It would further only work if all modules, that this file imports are already used by your frozen app.
So you see it's a little complicated, but I did something similiar with a py2exe application and with a pyinstaller application
Figured it out: I just compiled the Python script being called into an executable using Pyinstaller, and then called that executable. So my subprocess call above turned into:
command = "cmd.exe /C LaunchPPTKwin.exe"
self.child = QProcess()
self.child.start(command)
self.child.waitForFinished(-1)
I currently have a Python scrip that runs through all Excel files in the current directory and generates a PDF report.
It works fine now but I don't want the users to be anywhere near frozen Python scripts. I created an MSI with cxFreeze which puts the EXE and scripts in the Program Files directory.
What I would like to be able to do is create a shortcut to this executable and pass the directory the shortcut was run from to the Python program so that can be set as the working directory. This would allow the user to move the shortcut to any folder of Excel files and generate a report there.
Does Windows send the location of a opened shortcut to the executable and is there a way to access it from Python?
When you launch a shortcut, Windows changes the working directory to the directory specified in the shortcut, in the Start in field. At this point, Windows has no memory of where the shortcut was stored.
You could change the Start in field to point to the directory that the shortcut is in. But you'd have to do that for every single shortcut, and never make a mistake.
The better approach is to use a script, rather than a shortcut. Place your actual Python script (which we'll call doit.py for sake of example) somewhere in your PYTHONPATH. Then create a single-line Python script that imports it:
import doit
Save it (but don't name it doit.py) and copy it to each directory from which you want to be able to invoke the main script. In doit.py you can use os.getcwd() to find out what directory you're being invoked from.
You could also do it with a batch file. This is a little more flexible in that you can specify the exact name of the script and which Python interpreter should be used, and don't need to store the script in a directory in PYTHONPATH. Also, you don't need to worry about the file's name clashing with the name of a Python module. Simply put this line in a file:
C:\path\to\your\python.exe C:\path\to\your\script.py
Save it as (e.g.) doit.bat and copy it into the directories from which you want to invoke it. As before, your Python script can call os.getcwd() to get the directory. Or you can write it so your Python script accepts it as the first argument, and write your batch file like:
C:\path\to\your\python.exe C:\path\to\your\script.py %cd%
Another thing you can do with the batch file approach is add a pause command to the end so that the user is asked to press a key after the script runs, giving them the opportunity to read any output generated by the script. You could even make this conditional so that it only happens if an error occurs (which requires returning a proper exit code from the script). I'll leave that as an exercise. :-)
Is there a problem with modifying the script to take the directory to process as a command line argument?
You could then configure the different shortcuts to pass in the appropriate directory.
Type the following into a batch file (i.e. script.bat):
python \absolute\path\to\your\script.py %~dp0
pause
Then add these imports at the top of your python file script.py (if not already included):
import os
import sys
And add this to the bottom of the python file (or combine it with a similar statement):
if __name__ == "__main__":
# set current working directory:
if len(sys.argv) > 1:
os.chdir(sys.argv[1])
main()
replace main() with whatever function you want to call or code you want to run.
The following is how I came to my answer:
I tried using kindall's answer and had the following issues:
The first suggestion of storing the script somewhere in PYTHONPATH could not be applied to my situation because my script will be used on a server and needs to be independent of the client computer's python environment (besides having the required pip installations).
I tried calling my python script from a Windows Batch File which could be moved to a different location. Instead of the batch file's location being used as the current working directory, it was C:\Windows.
I tried passing %cd% as an argument to my python script, then setting that to be my CWD. This still resulted in a CWD of C:\Windows.
After reviewing the comments, I tried Eryk Sun's suggestion of instead passing %~dp0 as an argument to the python script. This resulted in the CWD being correctly set to the batch file's location.
I hope this helps others facing similar difficulties.
To clarify, the Python module I'm writing is a self-written .py file (named converter), not one that comes standard with the Python libraries.
Anyways, I want to somehow overload my function such that typing in
converter file_name
will send the file's name to
def converter(file_name):
# do something
I've been extensively searching through Google and StackOverflow, but can't find anything that doesn't require the use of special characters like $ or command line options like -c. Does anyone know how to do this?
You can use something like PyInstaller to create a exe out of your py-file.
To use the argument in python:
import sys
if __name__ == "__main__":
converter(sys.argv[1])
You can type in the windows shell:
python converter.py file_name.txt
to give the arguments to the sys.argv list within python. So to access them:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name.txt
at the bottom of the file you want to run, add:
if __name__ == "__main__":
converter(sys.argv[1])
To have a second argument:
python converter.py file_name1.txt file_name2.txt
This will be the result:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name1.txt
sys.argv[2] # this will be file_name2.txt
I would recommend using something like the builtin argparse (for 2.7/3.2+) or argparse on pypi (for 2.3+) if you're doing many complicated command line options.
Only way I can think of is to create a batch file of the same name and within it, call your python script with the parameters provided.
With batch files you don't have to specify the extension (.bat) so it gets you closer to where you want to be.
Also, without any compiling .py to .exe, you may make your script 'executable', so that if you issue command line like myscript param param, the system will search for myscript.py and run it for you, as if it was an .exe or .bat file.
In order to achieve this, configure the machine where you plan to run your script:
Make sure you have file associations set (.py to python interpreter, that is, if you doubleclick at your script in the explorer -- it gets executed). Normally this gets configured by the Python installer.
Edit the COMSPEC environment variable (look inside My Computer properties) to include .PY extension as well as .EXE, .COM, etc.
Start a fresh cmd.exe from Start menu to use the new value of variable. Old instances of any programs will see only old value.
This setup could be handy if you run many scripts on the same machine, and not so handy if you spread you scripts to many machines. In the latter case you better use py2exe converter to bundle up your application into a self-sufficient package (which doesn't require even python to be installed).
I've got a strange issue with importing a module. I've got a virtualenv setup and one module is available in {env}/lib/python2.6/site-packages/pkgname. There is a __init__.py file and pkgname.py inside.
Now, if I run {env}/bin/python and execute import pkgname.pkgname, it works just fine. But if I create a script in {env}/bin/pkgname.py with contents:
#!{env}/bin/python
import pkgname.pkgname
if __name__ == "__main__":
pkgname.pkgname.run()
this fails trying to import the same file again (since the package and the file have the same name). How can I disable looking in the same directory? Or how can I force the import to first look at the global packages?
Alternatively, what's the "proper" way of doing this? Just for consistency, I'd rather call my startup script the same as the actual package it's trying to run.
Call it pkgname. Done. OK, then it won't start if you doubleclick in it WIndows, but that's usually not a problem.
You can modify sys.path. It's just a list of paths to search and the current folder should be the first entry. Your file should run if you move the current folder to the end of the list. But I general I would not do something like that without a VERY good reason. Isn't it possible to rename your file name.py, runpkgname.py or something like that?
First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner
What I need exactly is :
a *.bat file that will run the script
a python script that will :
get all *_test.exe files in the current working directory
run all the files which were the result of the search
Best regards
import glob, os
def solution():
for fn in glob.glob("*_text.exe"):
os.startfile(fn)
If you copy this into a file, the script should do as you asked.
import os # Access the operating system.
def solution(): # Create a function for later.
for name in os.listdir(os.getcwd()):
if name.lower().endswith('_test.exe'):
os.startfile(name)
solution() # Execute this inside the CWD.