I have a folder of .py files written in Python 2.7 that I want to convert to Python 3 using the 2to3 tool. Using windows 10 in the cmd prompt i can convert a single file with the following command:
C:\Users\t\Desktop\search>python.exe 2to3.py -w graphicsDisplay.py
however this line is not syntactically correct when in python shell and ideally I'd like to be able to iterate through the whole folder and update all .py files using the by using the following python code in cmd:
C:\Users\t\Desktop\search>python
>>> import os
>>> for files in os.listdir('*filepath*'):
>>> if '.py' == str(files[-3:]):
>>> *...some line of code here to perform 2to3*
its the last line which I can't seem to get right so I guess my question is, how can I call the 2to3 function in python on each iteration of the files variable?
You can do it directly from command line
for %a in (*.py) do python.exe 2to3.py -w "%a"
For each file in the indicated set execute the conversion passing the for replaceable parameter (%a in this sample) that holds the reference to the file being iterated.
Looks like 2to3 support recursive folder checking if you leave out an explicit script to convert.
Would it be easier to have all your scripts in one folder and execute against that instead?
from: https://docs.python.org/2/library/2to3.html#
2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode
Related
I have a bash script which changes the path on my command line,
This one,
#!/usr/bin/env python
cd /mnt/vvc/username/deployment/
I have a python script which i wish to run after the path changes to the desired path,
The script,
#!/usr/bin/env python
import subprocess
import os
subprocess.call(['/home/username/new_file.sh'])
for folder in os.listdir(''):
print ('deploy_predict'+' '+folder)
I get this
File "/home/username/new_file.sh", line 2
cd /mnt/vvc/username/deployment/
^
SyntaxError: invalid syntax
Any suggestions on how can i fix this?thanks in advance
You need to explicitly tell subprocess which shell to run the sh file with. Probably one of the following:
subprocess.call(['sh', '/home/username/new_file.sh'])
subprocess.call(['bash', '/home/username/new_file.sh'])
However, this will not change the python program's working directory as the command is run in a separate context.
You want to do this to change the python program's working directory as it runs:
os.chdir('/mnt/vvc/username/deployment/')
But that's not really great practice. Probably better to just pass the path into os.listdir, and not change working directories:
os.listdir('/mnt/vvc/username/deployment/')
I encountered such a weird situation:
naivechou#naivechou/~>python test.py
test
naivechou#naivechou/~>pwd
/home/naivechou
naivechou#naivechou/~>python /home/naivechou/test.py
C:\toolchain\python\python.exe: can't open file '/home/naivechou/test.py': [Errno 2] No such file or directory
My working directory is /home/naivechou/, test.py is in there.
If I run test.py with absolute path, I'll get an error message of No such file or directory.But everything will be fine if I enter that directory and then run it. What's wrong with python?
Try moving into the folder where the python script is located and do a "ls" command there in Linux. if windows then do 'dir'. if you see the required file there then execute the following command
C:\location_where_the_script_is> python yourfile.py
For commands entered on the command line, Windows doesn't recognize forward-slashes as directory separators.
Your second example is looking in the current directory for the literal filename /home/naivechou/test.py, and of course such a filename does not exist.
Use backslashes instead, as is the Windows way:
python \home\naivechou\test.py
I currently have a PyInstaller packed Elf file and I'm looking to unpack it into the original .py file(s). I have been using PyInstaller Extractor but it appears to be telling the archive is not a PyInstaller archive.
Here is an example of what I've been doing:
$ cat main.py
#! /usr/bin/python3
print ("Hello %s" % ("World"))
I pack it in the file dist/main/main with the command:
pyinstaller main.py
Which outputs the file:
$ file dist/main/main
dist/main/main: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=373ec5dee826653796e927ac3d65c9a8ec7db9da, stripped
Now, when I want to unpack it:
$ python pyinstxtractor.py dist/main/main
[*] Processing dist/main/main
[*] Error : Unsupported pyinstaller version or not a pyinstaller archive
I don't understand why the file cannot be unpacked while I've been looking through many posts telling that this should be possible and I'm beginning to doubt it.
Is the unpacking of the ELF file actually possible?
Am I doing it the right away?
According to the Github page, this script is applicable only for Windows binaries. There is an archive_viewer.py script distributed with pyinstaller itself that allows to view binary contents and extract it. If you get a .pyz file after extraction, use archive_viewer.py on it again. IIRC, after all you will get .pyc files, which have to be decompiled.
On my system (Manjaro Linux) I've found this script at /lib/python3.6/site-packages/PyInstaller/utils/cliutils
It is also available as pyi-archive_viewer (at /usr/bin/pyi-archive_viewer) after installing to global interpreter.
Using pyi-archive_viewer CLI seems to be the supported solution, i.e. to print only the module names, recursively, and quit instead of prompting:
$ pyi-archive_viewer --log --recursive --brief build/PYZ-00.pyz
['__future__',
'_aix_support',
---SNIP---
'zipfile',
'zipimport']
But if you don't want to parse or unsafely eval() the CLI output, it seems to work to use the library directly:
from PyInstaller.utils.cliutils import archive_viewer
archive = archive_viewer.get_archive('build/PYZ-00.pyz')
output = []
archive_viewer.get_content(archive, recursive=True, brief=True, output=output)
# Now, output is ['__future__', '_aix_support', ---SNIP--- 'zipfile', 'zipimport']
This use of the library is undocumented, but it's essentially the same to what the CLI does given those flags.
Is there a way to convert a ui formed with qtDesigner to a python version to use without having an extra file?
I'm using Maya for this UI, and converting this UI file to a readable python version to implement would be really great!
You can use pyuic4 command on shell:
pyuic4 input.ui -o output.py
For pyqt5 you can use
pyuic5 xyz.ui > xyz.py
or
pyuic5 xyz.ui -o xyz.py
If you are using windows, the PyQt4 folder is not in the path by default, you have to go to it before trying to run it:
c:\Python27\Lib\site-packages\PyQt4\something> pyuic4.exe full/path/to/input.ui -o full/path/to/output.py
or call it using its full path
full/path/to/my/files> c:\Python27\Lib\site-packages\PyQt4\something\pyuic4.exe input.ui -o output.py
The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.
import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:
python uic.py input.ui -o output.py -x
You don't have to install PyQt4 with all its side features, you just need the PyQt4 package itself. Inside the package you could use the module pyuic.py ("C:\Python27\Lib\site-packages\PyQt4\uic") to convert your Ui file.
C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py -help
update python3: use pyuic5 -help # add filepath if needed. pyuic version = 4 or 5.
You will get all options listed:
Usage: pyuic4 [options] <ui-file>
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-p, --preview show a preview of the UI instead of generating code
-o FILE, --output=FILE
write generated code to FILE instead of stdout
-x, --execute generate extra code to test and display the class
-d, --debug show debug output
-i N, --indent=N set indent width to N spaces, tab if N is 0 [default:
4]
-w, --pyqt3-wrapper generate a PyQt v3 style wrapper
Code generation options:
--from-imports generate imports relative to '.'
--resource-suffix=SUFFIX
append SUFFIX to the basename of resource files
[default: _rc]
So your command will look like this:
C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py test_dialog.ui -o test.py -x
You could also use full file paths to your file to convert it.
Why do you want to convert it anyway? I prefer creating widgets in the designer and implement them with via the *.ui file. That makes it much more comfortable to edit it later. You could also write your own widget plugins and load them into the Qt Designer with full access. Having your ui hard coded doesn't makes it very flexible.
I reuse a lot of my ui's not only in Maya, also for Max, Nuke, etc.. If you have to change something software specific, you should try to inherit the class (with the parented ui file) from a more global point of view and patch or override the methods you have to adjust. That saves a lot of work time. Let me know if you have more questions about it.
I got some errors when I try to convert UI to PY and finally I found this solution.
First of all, if you couldn't find the pyuic5.bat file copy this code and paste it on your cmd:
C:\Users\Monster>cd Desktop
C:\Users\Monster\Desktop>python -m PyQt5.uic.pyuic -x trial.ui -o trial.py
And the problem has been solved easily!
Update for anyone using PyQt5 with python 3.x:
Open terminal (eg. Powershell, cmd etc.)
cd into the folder with your .ui file.
Type:
"C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py
for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat file is.
This should work!
For Ubuntu it works for following commands;
If you want individual files to contain main method to run the files individually, may be for testing purpose,
pyuic5 filename.ui -o filename.py -x
No main method in file, cannot run individually... try
pyuic5 filename.ui -o filename.py
Consider, I'm using PyQT5.
open cmd in directory where you have your file and type:
pyuic5 –x "filename".ui –o "filename".py
I've ran into the same problem recently. After finding the correct path to the pyuic4 file using the file finder I've ran:
C:\Users\ricckli.qgis2\python\plugins\qgis2leaf>C:\OSGeo4W64\bin\pyuic4 -o ui_q gis2leaf.py ui_qgis2leaf.ui
As you can see my ui file was placed in this folder...
QT Creator was installed separately and the pyuic4 file was placed there with the OSGEO4W installer
In case that you are using Pyside6, there is a 'uic' binary file (in windows, an exe file) in /Lib/site-packages/PySide6/
I want to run a python script without explicitly having to call "python" every time in my shell. I've tried to add the shebang #!/path/to/python but this does not seem to work. Does anyone know a work around this? Many thanks.
You've got to add the shebang:
#!/usr/bin/env python
Then make the script executable:
chmod +x foo
Then you can run it like any other executable:
./foo
And a note from Homer6: if you're editing the file from windows and invoking it on linux, you may run into the cryptic "No such file or directory" error. It's due to the line endings of the lines being CRLF instead of LF. If you convert them to LF, the script will execute as expected. Notepad++ > View > Show Symbols > Show End of Line to show the EOL characters. And Notepad++ > Edit > EOL Conversion > Unix Format to convert all line endings to use LF. Alternatively, you can use the dos2unix tool (dos2unix foo.py), which is present on most Linux systems.
It didn't really apply to your personal scripts but as you are quoting beets, note that it is also possible to automate this action when you are distributing your packages, thanks to setuptools entry_point option.
So if you are distributing a package like myModule and want to make the main_function() function accessible via typing mymodulescript in the console you would probably add something like this to your setup.py file :
setup(
# your other arguments ..
entry_points={
'console_scripts': [
'mymodulescript = myModule:main_function'
]
}
)
Add a line at the top of your script:
#! /usr/bin/env python
Rename your script from script_name.py to script_name
make the script executable: chmod +x script_name
The line at the top selects the same python that you get when typing python at the prompt. You can also specify a direct path:
#!/opt/python/3.6/bin/python
Another workaround could be to use an alias defined in the .bashrc :
e.g. add the following line in your .bachrc file :
alias mypythonalias="python mypyrhonfile.py"
type in terminal :
source ~/.bashrc
and then you may simply type:
mypythonalias
to execute the python file.
Ensure you are able to run /path/to/python on your terminal. And make sure you have given execute permission for your python file. You can give permission for the file by
chmod +x mypythonfile.py