Tag Archives: Python

C# call Python error no module named OS [How to Solve]

C # calling Python

Environment: Windows 8.1, has installed Python 2.7 (C: Python 27), has configured environment variables. Has installed vs2013, vs2017

1. Install ironpython

Download address http://ironpython.net/download/ I downloaded ironpython-2.7.4.3261515540.msi

The installation directory is: F:// program files (x86) – ironpython 2.7

2. Open vs2013 and create a new console program csharpcallpython

3. Add reference

Add a reference to csharpcallpython, ironpython.dll and microsoft.scripting.dll under F: (program files (x86)  ironpython 2.7  platforms  net40

4. Add the PY script file python1.py in csharpcallpython, and select to copy it locally. The code is as follows

def add(num1,num2):
    return num1+num2;

Add code in csharpcallpython

5

ScriptRuntime pyRuntime = Python.CreateRuntime(); //Create a runtime environment

        dynamic obj = pyRuntime.UseFile("Python1.py"); // call a Python file

        int a = 1, b = 2;

        int sum = obj.add(a,b); //call the sum function in the Python file
        Console.Write("Sum:");
        Console.WriteLine(sum);

The running result is sum = 3

This is the end of the call. Thank you. If this is possible, then it is impossible. Please see below

How to reference the third party Library

How to use the Library under OS?Let’s continue to add the PY script file python2.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import shutil


def ClearDirect(path):#

    for root, dirs, files in os.walk(path,topdown=False):
        print 'root',root
        for dir in dirs:

            print 'delete:',os.path.join(root, dir)
            #os.removedirs(os.path.join(root, dir))
            shutil.rmtree(os.path.join(root, dir))


    return 'OK'

The purpose of the script is to delete the subdirectory of the incoming directory and add C code

     ScriptRuntime pyRuntime2 = Python.CreateRuntime(); //Create a runtime environment
        dynamic obj2 = pyRuntime.UseFile("Python2.py"); // call a Python file
        obj2.ClearDirect(@"D:\Data\KkImage\2017"); //
        Console.Write("result");
        Console.WriteLine(sum); 

After running, I’m very sorry for the error

Unhandled exception of type "IronPython.Runtime.Exceptions.ImportException" in Microsoft.Dynamic.dll 

Additional information: No module named os  

The OS module was not found

7. How can I use the OS library

Add in python2.py

import sys
sys.path.append("F:\Program Files (x86)\IronPython 2.7\lib")

Code becomes

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sys.path.append("F:\Program Files (x86)\IronPython 2.7\lib")
import os
import shutil


def ClearDirect(path):#delete

    for root, dirs, files in os.walk(path,topdown=False):
        print 'root',root
        for dir in dirs:

            print 'delete:',os.path.join(root, dir)
            #os.removedirs(os.path.join(root, dir))
            shutil.rmtree(os.path.join(root, dir))


    return 'OK'

Run again, found subdirectory deleted successfully. Congratulations

8. In the Python code above, add

  sys.path.append("F:\Program Files (x86)\IronPython 2.7\lib")

When the program is released, the path on the server will change. If there are dozens of Python files, do you have to modify the path one by one?It’s horrible to think about it

So, you can use the following method. (first, remove the sentence “sys. Path. Append” in the python file (F: program files (x86) – ironpython 2.7 – lib “)

ScriptRuntime pyRuntime3 = Python.CreateRuntime(); //Create a runtime environment
            var engine = pyRuntime3.GetEngine("python");
            var pyScope = engine.CreateScope();
            var paths = engine.GetSearchPaths();
            paths.Add(@"F:\Program Files (x86)\IronPython 2.7\lib");
            engine.SetSearchPaths(paths);
            dynamic obj3 = pyRuntime3.UseFile("Python2.py"); //Calling a Python file
            obj3.ClearDirect(@"D:\Data\KkImage\2017"); //

If you specify the location of the library in the engine, you don’t need to specify it in each Python file

The problem of requirementparseerror in using Python paramiko package

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

Two problems encountered on March 14, 2017. The problem machine is a Windows Server, windows 2008 R2 standard 64 bit, Python 2.7.9

In fact, there are two problems mixed together. The first problem we encounter is:

No handlers could be found for logger "paramiko.transport"

This question is mixed with the second one below

The root of the problem is that the test code uses the logger of tornado. The root logger does not set the handlers, but sets the handlers (streamhandler) for the logger of ‘tornado. Application’. Therefore, the test code needs to be modified to set the default handler of root to nullhandler and the logger of ‘tornado. Application’ to streamhandler. Refer to test. Py in the sysmgt project( The essence is that the root logger does not set handlers, which causes other loggers to inherit it and have no handlers, and only the only set ‘tornado. Application’ logger can output normally.)

The second problem is that it still exists after the first problem is fixed. The error (simulation test) is as follows:

D:\temp\py>python paramiko_test.py
test paramiko ........
time1 : [0.0] - 10.99.201.174 - wcadmin
time1 : [0.0] - 10.122.2.6 - wcadmin
time2 : [0.0] - 10.99.201.174 - wcadmin
time2 : [0.0] - 10.122.2.6 - wcadmin
time3 : [0.0] - 10.99.201.174 - wcadmin
time3 : [0.0] - 10.122.2.6 - wcadmin
time4 : [0.0] - 10.99.201.174 - wcadmin - 
time4 : [0.0] - 10.122.2.6 - wcadmin - 
--- ip=10.99.201.174, username=wcadmin, password=
--- ip=10.122.2.6, username=wcadmin, password=
Traceback (most recent call last):
  File "paramiko_test.py", line 42, in one_connection
    sshclient.connect(ip, 22, username, password)
  File "C:\app\Python27\lib\site-packages\paramiko\client.py", line 338, in connect
    t.start_client(timeout=timeout)
  File "C:\app\Python27\lib\site-packages\paramiko\transport.py", line 500, in start_client
    raise e
RequirementParseError: Invalid requirement, parse error at "''"
time5 : [0.452000141144] - 10.99.201.174 - wcadmin
time6 : [0.46799993515] - 10.99.201.174 - wcadmin

The above is the test result of the test program (multi thread connection to the remote server). The same program has no problem on my own computer

Requirement parseError: invalid requirement this problem is not that every time you run the test program, you will make an error. The probability of error is 85%

Solution process:

1 suspected the problem of out of date PIP version, and finally uninstalled and installed it. Because the old version of PIP was not found, it was a new version before and after pip. It turned out that it had nothing to do with PIP

2. The version of paramiko is suspected. Upgrade paramiko from 1. * to 2 +. There are still problems

3. According to the similar problem on the Internet, that is to say, it’s a problem with the setup tools library. Uninstall it, then install it, and report that the module appdirs can’t be found. Download and install the module appdirs. Then install a new version of setup tools to solve the problem

The old version of setup tools is 22.0.0, while the new one is 34.3.2. My version is 16.0. So it seems that a version of setuptools conflicts with paramiko. Demote the version of setuptools on the server and solve the problem

On March 15, it was found that although the setup tools on the server were demoted, there was no problem in the test at that time, but in fact there was no in-depth test, and there was still the same problem after more threads were concurrent

So I uninstall and install the latest version of the setup tools on my computer, and the problem on the server is reproduced. When testing on Linux machines, there are also problems with the higher versions of setuptools. Next, I found an article about reducing the version of setuptools to 20.2. So the final version is 19.7, which has no problem after testing

I don’t know if the problem will recur. Let’s see

On March 15, I repeatedly installed and uninstalled setup tools and pip on the server side. I found some problems, but I didn’t understand them very well

1pkg_ The resources module, for reference, should be used to load the module. After Python is installed, it appears in $python_ When installing the latest PIP and setup tools in home/lib/site packages, we sometimes find that PKG in site packages_ Resources is no longer available, but appears in setuptools

2. After installing and uninstalling PIP setuptools for many times, we found that pip.exe and pip-script.py were missing, which made PIP unusable. Because we operated for many times, we didn’t know which time this problem occurred, so we had to use these two files on other machines. I don’t know if other files are missing

To solve the second problem, find a way on the Internet and execute the following command:

python -m pip install --upgrade pip --force-reinstall

This article was published in open source China. At that time, I thought that the problem had been solved, but the problem still existed the next day. As a result, I continued to search on the Internet and found that this article had been reprinted by a website. I estimated that it was automatically published through web crawler, so I updated it today, and I’ll see if it will be crawled in a few days

My test program:

#-*-coding:UTF-8-*-

__author__='zhaoxp'

import traceback
import logging
import time
import threading

import paramiko

logging.basicConfig(level=logging.DEBUG)
logging.getLogger().handlers=[logging.NullHandler()]
logger = logging.getLogger('paramiko.test')
logger.handlers.append(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

def main():
    threads = []
    threads.append(threading.Thread(target=one_connection, args=('10.99.201.174', 'wcadmin', 'password')))
    threads.append(threading.Thread(target=one_connection, args=('10.122.2.6', 'wcadmin', 'password')))
    threads.append(threading.Thread(target=one_connection, args=('10.99.201.37', 'wcadmin', 'password')))
    threads.append(threading.Thread(target=one_connection, args=('10.99.244.121', 'wcadmin', 'password')))
    for th in threads:
        th.start()
    for th in threads:
        th.join()


def one_connection(ip, username, password):
    sshclient = None
    try:
        start_time = time.time()
        logger.debug('time1 : [%s] - %s - %s'%(time.time()-start_time, ip, username))
        sshclient=paramiko.SSHClient()
        logger.debug('time2 : [%s] - %s - %s'%(time.time()-start_time, ip, username))
        sshclient.load_system_host_keys()
        logger.debug('time3 : [%s] - %s - %s'%(time.time()-start_time, ip, username))
        sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        logger.debug('time4 : [%s] - %s - %s - %s'%(time.time()-start_time, ip, username, password))
        logger.debug('--- ip=%s, username=%s, password=%s'%(ip, username, password))
        sshclient.connect(ip, 22, username, password)
        logger.debug('time5 : [%s] - %s - %s'%(time.time()-start_time, ip, username))
        stdin, stdout, stderr = sshclient.exec_command('pwd')
        #logger.debug('stdout:\n%s \n stderr:\n%s \n'%(stdout.read(), stderr.read()))
        logger.debug('time6 : [%s] - %s - %s'%(time.time()-start_time, ip, username))
    except BaseException as be:
        traceback.print_exc()
    finally:
        if sshclient is not None:
            sshclient.close()

if __name__=='__main__':
    print 'test paramiko ........'
    main()

[Solved] PythonTypeError: ‘<' not supported between instances of 'str' and 'int'

1 n = input()
2 if n>=100:print(int(n)/10)
3 else:print(int(n)*10)

Error:

Traceback (most recent call last):
  File "1.py", line 12, in <module>
    if n>=100:print(int(n)/10)
TypeError: '>=' not supported between instances of 'str' and 'int'

***Repl Closed***

analysis: the data type returned by input() is STR, which cannot be directly compared with integers. You must first replace STR with integers, and use the int() method

therefore, the input variable can be converted to int

1 n = input()
2 n = int(n)
3 if n>=100:print(int(n)/10)
4 else:print(int(n)*10)

Or

1 n = int(input("Input a number:"))
2 if n>=100:print(int(n)/10)
3 else:print(int(n)*10)

 

Python uses decorator and reports error typeerror: ‘nonetype’ object is not callable ‘

In the process of learning python, write a decorator according to the example of online tutorial https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584#0 )Type error: ‘nonetype’ object is not callable ‘

The code is as follows:

1 def log(func) :
2     def wrapper():
3         print('time:')
4         func()
5     return wrapper()
6 @log
7 def show():
8     print('2019')
9 show()

The results of normal operation should be as follows:

time:
2019

After searching around the Internet, they all said that the solution was to remove the “()” in the last function call statement, and there was no other explanation. But I feel that there is a problem, so make a note

After removing, it is found that there is no error, and the result can be displayed normally. But this kind of operation obviously violates our basic common sense of writing code( In addition to the special syntax, there is generally no function that can be called directly only through the function name.)

In fact, from the error message, we can guess that the show function could not be called. After testing with the code, we found that show has indeed become a non type

def log(func) :
    def wrapper():
        print('time:')
        func()
    return wrapper()
@log
def show():
    print('2019')
if show is None:
    print("True")

Results of operation:

time:
2019
True

After the test, we found that not only show has become a non type, but also the operation of calling show has been executed. In fact, according to the writing method in the tutorial, the function call has been completed in the “@ log” statement, and there is no need to call it again. The last line of code is actually redundant. Moreover, this “@ log” writing method also changes the type of the show function“

Putting @ log in the definition of show() function is equivalent to executing a statement:

show= log(show)

”This function cannot be called in the usual way later. I don’t know the specific mechanism yet. Or there’s some other way to repeat the call. It will be added later

if there are any mistakes in the expression or concept in the article, please reply

Python calls shell script: oserror: [errno 8] exec format err

Knowledge map advanced must read: read how large-scale map data efficient storage and retrieval>>>

Recently, we encountered a script call problem in the company project. A python command-line tool started a zookeeper shell script using the subprocess module, and reported an error during execution: oserror: [errno 8] exec format error, as shown in the figure below:

At this point, I try to execute the shell script in the red box on the command line : is executed successfully, indicates that it is not a shell script problem

Then, I suspected that there was a problem with the permission of Python. I checked it online and said that I wanted to add a Python interpreter ( #)/ Usr/env/Python ), so I checked the content of the corresponding Python file: confirm that it contains / usr/env/python


Then I worried about the issue of execution permission , so modified the executable permission of Python and shell scripts: but still did not solve the problem

chmod+xXXX.pychmod+x/etc/init.d/zookeeper

Finally, I suspect that there is something wrong with the shell script interpreter . At this time, I open the shell script (/etc/init. D/zookeeper ) and find that there is no / bin/sh

As we know, shell scripts can be executed in two ways:

1. sh XXX.sh

2. chmod +XXX.sh; ./ XXX.sh

For the second mode of operation, the script must contain a shell interpreter

As shown in the figure below, I added a shell interpreter (#)/ After that, the python script calls the shell script and does not report an error

So far, the problem has been solved

The debugging process is divided into three steps

1. Execute the shell script manually: see if the script itself has problems, and ignore the problem of calling the shell by python

2. Check the executable permissions: both shell and python scripts should ensure that the user has executable permissions. If you don’t feel at ease, use the script corresponding to Chmod + X

3. Check the interpreter of the script: because the script is an interpretive language (you need to specify an interpreter to execute line by line), it is not a compiled language (you don’t need to translate and interpret line by line after compiling). If there is no interpreter, the script may not be executable

Blogger: testing makes money

Motto: test to complete the original accumulation, invest to financial freedom

csdn: https://blog.csdn.net/ccgshigao

Blog Park: https://www.cnblogs.com/qa-freeroad/

51cto: https://blog.51cto.com/14900374

In this article, we share the blog “test makes money” (51CTO).

[Solved] Python import module error: importerror: no module named mysql.connector

The version of Python is

$ python --version
Python 2.7.12

The error code is as follows

importmysql.connector

The error message is

ImportError:Nomodulenamedmysql.connector

The driver installed at the beginning is that the installation was successful

$ pipinstallmysql-connector

But if you install MySQL connector python, you will report an error

Collecting mysql-connector-python
  Could not find a version that satisfies the requirement mysql-connector-python (from versions: ) No matching distribution found for mysql-connector-python

So now the driver is MySQL connector instead of MySQL connector Python
ask for help from an experienced friend

The problem has been solved

The steps are as follows:

Execute PIP search MySQL connector | grep -- color MySQL connector Python

The output is like this

mysql-connector-python-rf (2.1.3)        - MySQL driver written in Python mysql-connector-python (2.0.4) - MySQL driver written in Python

Usepip install mysql-connector-python-rf==2.1.3 is ok

python Warning: OverflowError: Python int too large to convert to C long

Once, when using ORM to perform a join table query, there was a problem with Python int too large to convert to C long

After analyzing the error, the last prompt of the error is as follows:

File "F:\python\python3.6\lib\sqlite3\dbapi2.py", line 64, in convert_date
    return datetime.date(*map(int, val.split(b"-")))

When viewing my model.py file, my model definition is as follows:

from django.db import models


# Create your models here.

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=64)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)

    authors = models.ManyToManyField(to="Author")


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    AuthorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    # birthday = models.DateField()  # In particular, this line is commented out so that it no longer prompts Python int too large to convert to C long
    tetephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

Python: `if not x:` VS `if x is not None:` VS `if not x is None:`

There are three main ways to judge whether a variable is none in code

The first is’ if x is none ‘

The second is’ if not X: ‘

The third is “if not x is none”

If you think it doesn’t make any difference, you should be careful. There is a hole in it. Let’s look at the code first

>>>x=1
>>>notx
False
>>>x=[1]
>>>notx
False
>>>x=0
>>>notx
True
>>>x=[0]#Youdon'twanttofallinthisone.
>>>notx
False

In Python, none, false, empty string “” 0, empty list [, empty dictionary {}, empty tuple () are equivalent to false, that is:

<strong>notNone==notFalse==not''==not0==not[]==not{}==not()</strong>

Therefore, when using the list, if you want to distinguish between X = = [] and x = = none, there will be a problem with ‘if not X:’:

>>>x=[]
>>>y=None
>>>
>>>xisNone
False
>>>yisNone
True
>>>
>>>
>>>notx
True
>>>noty
True
>>>
>>>
>>>notxisNone
>>>True
>>>notyisNone
False
>>>

Maybe you want to judge whether x is none or not, but you also judge the case of ‘x = =]’, in which case you will not be able to distinguish

for those who are used to using the writing method of if not x, it must be clear that when x equals none, false, empty string “” 0, empty list [], empty dictionary {}, empty tuple (), it will not affect your judgment

As for the writing of ‘if x is not none’ and ‘if not x is none’, it is obvious that the former is clearer, while the latter may make readers misunderstand it as’ if (not x) is none ‘, so the former is recommended, which is also the style of Google recommendation
at the same time

conclusion:

‘if x is not none’ is the best way to write. It is clear and will not make mistakes. I will insist on using this way in the future

the premise of using if not x is: it must be clear that when x equals none, false, empty string “” 0, empty list [], empty dictionary {}, empty tuple (), it will not affect your judgment

================================================================

However, this does not apply to the case where the variable is a function, which is reproduced from: https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md

The difference between foo is none and foo = = none

Question link

if foo is None: pass
if foo == None: pass

If the same object instance is compared, is always returns true and = = depends on “ EQ ()”

>>> class foo(object):
    def __eq__(self, other):
        return True

>>> f = foo()
>>> f == None
True
>>> f is None
False

>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list1==list2
True
>>> list1 is list2
False

In addition

(ob1 is ob2) IS (id(ob1) == id(ob2))

################################################################################

Supplement, 2013.10.09

What does not mean in Python?For example, thank you very much

In python not is a logical judgment word for boolean True and False, not True for False and not False for True. Here are a few common uses of not.
(1) not is used in conjunction with the logical judgment sentence if, representing the statement after the colon is executed when the expression after not is False. For example
a = False
if not a: (Here, because a is False, not a is True)
    print "hello"
Here we can output the result hello
(2) Determine whether the element is in the list or dictionary, if a not in b, a is the element, b is the list or dictionary, this sentence means that if a is not in the list b, then execute the statement after the colon, for example
a = 5
b = [1, 2, 3]
if a is not in b:
    print "hello"
The result hello can also be output here
not x is equivalent to     if x is false, then True, else False

Python Attempted relative import in non-package,ImportError: cannot import name ‘xx’ from ‘__main

Problem introduction

When writing a python script, you want to extract the configuration shared by the two scripts to form a configuration file, and read the configuration file when running the script

Script tool directory structure:

	programoperater
		__init__.py
		autorun_startprogram.py		
		autorun_checkstart.py	
		programsetting.py	

In the script, import the configuration file through the relative path:

from . import programsetting

In the server, use your own installed Python 3.7.3 to report an error:

use the server’s own Python 2.7.5 to report an error:

Problem analysis, that is, python package mechanism

Official explanation: relative imports use a module’s name attribute to determine that module’s position in the package hierarchy__ name__ To achieve

Through “from. Import programsetting g”, programsetting obtains the “programoperator. Program”__ name__ Property. The premise is that the program operator is recognized by the Python interpreter as a package for processing (for example, run.py running in the peer folder of the program operator has statements such as import program operator. Program)

newfolder/
└─ programoperater
│		__init__.py
│		autorun_startprogram.py	
│		autorun_checkstart.py	
│		programsetting.py		
│
└─ run.py

there is a problem that causes me to quote packages:
scripts that I run directly will be regarded as top-level scripts. Top level script__ name__ Is automatically set to__ main__。 So if I run autorun directly from inside the program operator folder_ Checkstart. Py, then its__ name__ It’s set up__ main__, Python will not treat it as a package, and the relative import statement will not work

Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.

Solutions

change directory structure:

 programoperater
 │ 	 	__init__.py
 │   	autorun_checkstart.py
 │    	autorun_startprograms.py
 │  
 └─settings
         __init__.py
         programsetting.py

modification of package introduction mode:

from settings import programsetting

Through this modification, you can directly run the specified script autorun_ checkstart.py

Interpretation of the Official Website Package Mechanism: https://docs.python.org/zh-cn/3/tutorial/modules.html#packages

Error interpreter field is empty when installing pychar to create a new project. Run the python program

Detailed map traversal, teach you to master the complex gremlin query debugging method>>>

Error interpreter field is empty when installing pychar to create a new project. Run the python program

September 13, 2018 17:08:43 flyingong read 518 more

Personal category: software installation

Copyright notice: reprint casually and indicate the source. If you don’t make money, you just make friends. https://blog.csdn.net/a1194110603/article/details/82690932

Reason: the Python interpreter is not installed

Steps to install Python:

1. Download the installation package from the official website, and choose the latest version

https://www.python.org/downloads/

2. To install python, refer to the Python installation section of the following blog for specific steps, and remember the installation path:

https://www.cnblogs.com/weven/p/7252917.html

3. Start pychar, create a new project, and select the directory to install Python in the blue box to find the location of python.exe

4. Right click New Python file in the folder you created, create a python file, and double-click to program

5. Input command

print('Hello World !');

Then click as shown in the figure and select the programming file to run the first Python program. After that, you can click the right triangle to run directly

At present, mobile phones are popular ways to make money. People who know Huada have already made money crazy! Xinzhou Trade Co., Ltd