Remove Cython assertion option in setup.py - python-3.x

My Cython (.pyx) file contains assert and I would like to remove it when I compile the file. I found this post and edited my setup.py as follows.
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# Before edit
compiler_args = ["-O3", "-ffast-math"]
# Both did not work
# compiler_args = ["-O3", "-ffast-math", "-DPYREX_WITHOUT_ASSERTIONS"]
# compiler_args = ["-O3", "-ffast-math", "-CYTHON_WITHOUT_ASSERTIONS"]
ext_modules = [
Extension("mycython", sources=["mycython.pyx"],
extra_compile_args=compiler_args)
]
setup(
name="Test",
cmdclass={'build_ext': build_ext},
ext_modules=ext_modules
)
The error says:
clang: error: unknown argument: '-CYTHON_WITHOUT_ASSERTIONS'
How can I fix it?

CYTHON_WITHOUT_ASSERTIONS is a preprocessor macro, so you have to pass it to clang with the -D flag (just like gcc). The first variable's name is actually PYREX_WITHOUT_ASSERTIONS, but to pass it to the preprocessor as a macro (i.e. a part of your clang compiler) you need to add a -D in front of the variable name.
Try compiler_args = ["-O3", "-ffast-math", "-DCYTHON_WITHOUT_ASSERTIONS"] instead (note the D in front of CYTHON_WITHOUT_ASSERTIONS).
HTH.

Related

Python list not sorting when called from inside a bash script

I am trying to print a custom help message for a bash script. Inside the script, I call a function that then uses python to parse the script, find the functions and the function help string, and then print them. This all works. But, when I try to sort the list of tuples that contains the function name and help string, the sort seems to be ignored. Similar code works as expected in a pure python environment.
Edit: Just noticed I tried the sort two different ways. AFAIK either should have sorted the list, but neither worked.
Edit again: see the accepted answer below for code that actually works. I need to remember to reread my problem code in the morning ;)
SCRIPT_PATH=$(realpath $0)
function build() { ## builds source and wheel package
echo "foo"
}
function aa() { ## foo
echo "foo"
}
function release() { ## package and upload a release
echo "foo"
}
function project:init:all() { ## Initialize a venv, update pip, wheels, and setuptools, and install both requirements files.
echo "foo"
}
function venv:init() { ## makes a venv in the project directory
echo "foo"
}
function print:help() {
echo $SCRIPT_PATH
python3 - << EOF
from pathlib import Path
from operator import itemgetter
import re
script_path = Path("$SCRIPT_PATH")
with open(script_path) as file:
for line in file:
match = re.match(r'^function\s*([a-zA-Z0-9\:-]*)\(\)\s*{\s*##\s*(.*)', line)
matches = []
if match is not None:
target, help = match.groups()
matches.append((target,help))
#for help_line in sorted(matches,key=lambda func: func[1]):
matches.sort(key=itemgetter(1))
for help_line in matches:
print(" {0:20} {1}".format(target,help))
EOF
}
results in:
build builds source and wheel package
aa foo
release package and upload a release
project:init:all Initialize a venv, update pip, wheels, and setuptools, and install both requirements files.
venv:init makes a venv in the project directory
but I expected:
aa foo
build builds source and wheel package
project:init:all Initialize a venv, update pip, wheels, and setuptools, and install both requirements files.
release package and upload a release
venv:init makes a venv in the project directory
You need to get all the functions, then sort and print :
function print:help() {
echo $SCRIPT_PATH
python3 - << EOF
from pathlib import Path
from operator import itemgetter
import re
script_path = Path("$SCRIPT_PATH")
with open(script_path) as file:
functions = []
for line in file:
match = re.match(r'^function\s*([a-zA-Z0-9\:-]*)\(\)\s*{\s*##\s*(.*)', line)
if match is not None:
functions.append(match.groups())
for target, help in sorted(functions):
print(" {0:20} {1}".format(target,help))
EOF
}

Why is pytest giving me an "unrecognized option" error when I try and create a custom command line option?

I'm using Python 3.8 and pytest 6.0.1. How do I create a custom command line option for pytest? I thought it was as simple as adding this to conftest.py ...
def pytest_addoption(parser):
    parser.addoption('--option1', action='store_const', const=True)
but when I pytest, I get an unrecognized option error
# pytest --option1=Y -c tests/my_test.py
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --option1=Y
What's the right way to add a custom option?
Edit: I tried the answer given. I included some other things in my tests/conftest.py file in case those are the reason the answer isn't working. File contains
def pytest_generate_tests(metafunc):
option1value = metafunc.config.getoption("--option1")
print(f'Option1 Value = {option1value}')
def pytest_configure(config):
use_docker = False
try:
use_docker = config.getoption("--docker-compose-remove-volumes")
except:
pass
plugin_name = 'wait_for_docker' if use_docker else 'wait_for_server'
if not config.pluginmanager.has_plugin(plugin_name):
config.pluginmanager.import_plugin("tests.plugins.{}".format(plugin_name))
But output when running is
$ pytest -s --option1 tests/shared/model/test_crud_functions.py
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --option1
inifile: /Users/davea/Documents/workspace/my_project/pytest.ini
rootdir: /Users/davea/Documents/workspace/my_project
As already mentioned in a comment action='store_const' makes your option a flag. The value you receive when you read option value provided it is specified on cli is the one specified by const i.e. True in your case.
Try this:
add below function to conftest.py
def pytest_generate_tests(metafunc):
option1value = metafunc.config.getoption("--option1")
print(f'Option1 Value = {option1value}')
pytest invoked with option pytest -s --option1
Output will have : Option1 Value = True
pytest invoked without option pytest -s
Output will have : Option1 Value = None
action=store might give you the desired behavior.
Solution:
# Change the action associated with your option to action='store'
def pytest_addoption(parser):
parser.addoption('--option1', action='store')
def pytest_configure(config):
x = config.getoption('option1')
print(x) # Any logic that uses option value
Output:
pytest -s --option1=Y -c=test.py
Y
============================================================================= test session starts ==============================================================================
platform darwin -- Python 3.8.5, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
You can find details on available action(s) and more here: https://docs.python.org/3/library/argparse.html#action
I think order matters in this case.
Try pytest -c tests/my_test.py --option1=Y

Getting FileNotFoundError when calling python coded file from robot framework

I am trying to write an automation code for picking up different environment values for execution of my testcases based on the value I pass for environment.
Here is the code I tried :
# env.robot
*** Settings ***
Variables setup.py stage01
*** Test Cases ***
Print values
log to console ${data}
# setup.py
from robot.libraries.BuiltIn import BuiltIn
import xlrd
def get_variables(env):
file_location = "values.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_name(env)
print("Env : " + sheet.name)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
print(data)
BuiltIn().log_to_console(data)
return data
Response I am getting :
[ ERROR ] Error in file 'D:\env.robot': Processing variable file 'D:\setup2.py' with arguments [ stage01 ]
failed: FileNotFoundError: [Errno 2] No such file or directory: 'values.xlsx'
values.xlsx is present in the same directory with .py and .robot file
I want to get the data from values.xlsx file based on the value of env variable and use the values in robot testcases.
Please suggest what I need to modify or any other approach would also do.

How to Return List of Packages from Pacman/Yaourt Search

----EDIT----
Changed the name of the script from pacsearch to pacdot.
Apparently yaourt -Ssaq does this, so this script isn't as necessary as I thought. Although, I still find using pacdot -w to open the results in a text document helpful.
----/EDIT----
This isn't a question, but I thought someone else might find this useful. Someone may end up on stackoverflow trying to find a solution like this.
On Arch Linux, I keep finding myself searching with pacman or yaourt and wishing I could get just the package names, not all of the extra stuff. For example, I'd love to be able to run yaourt -Sa $(yaourt -Ssa package). Oddly enough, pacman and yaourt don't seem have this option (not that I can tell, at least), so I wrote a python script to do it. Copy it if you'd like. You can name it what you want, but I'll refer to it as pacdot.py.
pacdot.py package will be like yaourt -Ssa package but only list the package names.
I added a few extra options:
pacdot.py -o package will only list results from the official Arch repositories, not the AUR.
pacdot.py -i package will install all the found packages. If you've ever thought about running something like yaourt -Sa $(yaourt -Ssa package), that's what this command does.
pacdot.py -w package will:
Create a file called 'the-package-you-searched.txt',
Write an example command that would install the found packages,
(yaourt -Sa all-of-the-results),
Write each result on a new line, and
Open the file for you (with your default text editor).
Here's the code:
#!/bin/python3
import argparse
import re
from subprocess import Popen, PIPE, call
from collections import deque
desc = ''.join(('Search the official Arch and AUR databases ',
'and return package names only. ',
'e.g.: `pacdot.py arch` will return "arch", ',
'whereas `$ yaourt -Ssa arch` will return ',
'"community/arch 1.3.5-10',
' A modern and remarkable revision control system."'
))
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('package',
help='Package to search with pacman')
parser.add_argument('-o', '--official', action='store_true',
help='Search official repositories only, not the AUR')
parser.add_argument('-i', '--install', action='store_true',
help='Install found packages')
parser.add_argument('-w', '--write', action='store_true',
help='Write to file')
#Set args strings.
args = parser.parse_args()
pkg = args.package
official_only = args.official
install = args.install
write = args.write
# Do yaourt search.
package_search = Popen(['yaourt', '-Ssa', '%s' % pkg], stdout=PIPE).communicate()
# Put each found package into a list.
package_titles_descs = str(package_search[0]).split('\\n')
# Strip off the packages descriptions.
package_titles = [package_titles_descs[i]
for i in range(0, len(package_titles_descs), 2)]
# Remove empty item in list.
del(package_titles[-1])
# Make a separate list of the non-aur packages.
package_titles_official = deque(package_titles)
[package_titles_official.remove(p)
for p in package_titles if p.startswith('aur')]
# Strip off extra stuff like repository names and version numbers.
packages_all = [re.sub('([^/]+)/([^\s]+) (.*)',
r'\2', str(p))
for p in package_titles]
packages_official = [re.sub('([^/]+)/([^\s]+) (.*)',
r'\2', str(p))
for p in package_titles_official]
# Mark the aur packages.
# (Not needed, just in case you want to modify this script.)
#packages_aur = packages_all[len(packages_official):]
# Set target packages to 'all' or 'official repos only'
# based on argparse arguments.
if official_only:
packages = packages_official
else:
packages = packages_all
# Print the good stuff.
for p in packages:
print(p)
if write:
# Write results to file.
filename = ''.join((pkg, '.txt'))
with open(filename, 'a') as f:
print(''.join(('Yaourt search for "', pkg, '"\n')), file=f)
print('To install:', file=f)
packages_string = ' '.join(packages)
print(' '.join(('yaourt -Sa', packages_string)), file=f)
print('\nPackage list:', file=f)
for p in packages:
print(p, file=f)
# Open file.
call(('xdg-open', filename))
if install:
# Install packages with yaourt.
for p in packages:
print(''.join(('\n\033[1;32m==> ', '\033[1;37m', p,
'\033[0m')))
Popen(['yaourt', '-Sa', '%s' % p]).communicate()
You've just re-invented the wheel. pacman, packer and yaourt all have the -q flag.
For example:
yaourt -Ssq coreutils
Results:
coreutils
busybox-coreutils
coreutils-git
coreutils-icp
coreutils-selinux
coreutils-static
cv
cv-git
ecp
gnu2busybox-coreutils
gnu2plan9-coreutils
gnu2posix2001-coreutils
gnu2sysv-coreutils
gnu2ucb-coreutils
policycoreutils
selinux-usr-policycoreutils-old
smack-coreutils
xml-coreutils

Python 3.3:cx_freeze & pyserial: cannot import traceback module

I'm newbie in cx_freeze. I'm triing to make an executable from python 3.3 script that uses "time", "serial" and "tkinter".
Cx_freeze run without any errors, but starting the exe file is resulting with error:
cannot import traceback module
Exception: No module named 're'
Original Exception: No module named 'serial'
I have this setup.py of cx_freeze
from cx_Freeze import setup, Executable
includes = ["serial", "tkinter"]
excludes = []
packages = []
path = []
GUI2Exe_Target_1 = Executable(
# what to build
script ='test6.1.py',
initScript = None,
base = 'Win32GUI',
targetDir = r"dist",
targetName = "bludiste2.exe",
compress = True,
copyDependentFiles = True,
appendScriptToExe = False,
appendScriptToLibrary = False,
icon = None
)
Does anyone know, how to solve it, please?
Thank you.
The first two lines are a bug that will be fixed in the next version of cx_Freeze. If you stick an import re in your script, you'll see the correct error message.
The last line is your real problem - that means it didn't find the serial module when you froze it. Check where pyserial is installed on your computer.

Resources