I'm having problem with listing home directory of current user without knowing absolute path to it. I've tried with the following, but it doesn't work:
[root#blackbox source]# python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:38:36)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('/root')
['python', '.bashrc', '.viminfo']
>>> os.listdir('~')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~'
>>>
You need to use the os.path.expanduser() function:
>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
You could ask the Operation System like this:
>>> import os
>>> os.environ['HOME']
'/home/noctua'
>>> os.listdir(os.environ['HOME'])
Related
This is my python Code to see the Devices connected to my WIFI:
import subprocess
meta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
data = meta_data.decode('utf-8', errors="backslashreplace")
data = data.split('\n')
names = []
for i in data:
if "All Users Profiles" in i:
i = i.split(":")
i = i[1]
i = i[1:-1]
names.append(i)
print("Systems Connected To Your WIFI ARE ")
print()
for name in names:
print(name)
AND this is the error I keep getting after i run the code:
FileNotFoundError: [Errno 2] No such file or directory: 'netsh'
You need to call it through the shell using cmd.exe /c or by passing shell=true into check_output. The subprocess package does not run in a shell by default on Windows.
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.check_output(["dir"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>> subprocess.check_output(["cmd.exe","/c","dir"])
b' ... '
>>> subprocess.check_output(["dir"], shell=True)
b' ... '
This is only something you need to do on Windows.
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.check_output(["ls"])
b' ... '
How to start a windows application like notepad using python NET ? This is my source code with python 2.7.13:
C:\Python27>python.exe
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import System
>>> type = System.Type.GetTypeFromProgID("Notepad.Application")
>>> System.Activator.CreateInstance(type)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
System.ArgumentNullException: Value cannot be null.
Parameter name: activationContext
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
There is no ProgID="Notepad.Application" COM object on my machine, pythonnet works with other COM objects:
>>> import clr
>>> import System
>>> type1=System.Type.GetTypeFromProgID("Excel.Application")
>>> type1
<System.RuntimeType object at 0x02ABEE10>
>>> System.Activator.CreateInstance(type1)
<Microsoft.Office.Interop.Excel.ApplicationClass object at 0x02AD11D0>
this simple python program that is extracted from more complex codebase:
#insp.py
import inspect
L = lambda x: x+1
print("L(10)=" + str(L(10)))
code = inspect.getsource(L)
print(code)
works if i run it from the command line as:
$ python insp.py
If I copy and paste each line in the python interpreter it fails:
d:\>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> L = lambda x: x+1
>>> print("L(10)=" + str(L(10)))
L(10)=11
>>> code = inspect.getsource(L)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 944, in getsource
lines, lnum = getsourcelines(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 762, in findsource
raise OSError('could not get source code')
OSError: could not get source code
Note that using IPython instead of the plain Python interpreter, it works!
Does anybody know why?
I use Python 3.5 32 bits under Windows7.
It works in IPython because it caches each and every command you enter there using linecache module.
For example:
$ ipy ## Equivalent to ipython --classic
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
Type "copyright", "credits" or "license" for more information.
IPython 3.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
>>> print a
Traceback (most recent call last):
File "<ipython-input-1-9d7b17ad5387>", line 1, in <module>
print a
NameError: name 'a' is not defined
Notice the <ipython-input-1-9d7b17ad5387> part here, this is something specific to IPython. In normal Python shell you would see <stdin>:
$ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Now let's run your code:
>>> import inspect
>>> L = lambda x: x+1
>>> code = inspect.getsource(L)
Time to find out the filename related to L:
>>> L.func_code.co_filename
'<ipython-input-2-0c0d6f325784>'
Now let's see if we have the source in linecache.cache for this file:
>>> import linecache
>>> linecache.cache[L.func_code.co_filename]
(18, 1481047125.479239, [u'L = lambda x: x+1\n'], '<ipython-input-2-0c0d6f325784>')
So, using this information IPython is able to find the required source but Python shell doesn't because it is not storing any.
The related details about how inspect gets the source can be found in getsourcefile and findsource functions in the source code.
I am trying to import a package present in another folder and it is working perfectly fine in python 3.4. For Example: the files are present in libraries folder
user> python
Python 3.4.1 (default, Nov 12 2014, 13:34:29)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
>>>
However when I open a new shell and use Python 2.7:
user> python
Python 2.7.4 (default, Jun 1 2015, 10:35:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
>>>
I tried adding the entry to sys.path but it is not helping. I read a similar question here but the solution is not helping me either as I tried both relative and absolute imports. Please advice.
EDIT: The directory structure being ~/tests/libraries/controller_utils.py. I am executing these commands inside the tests directory.
EDIT: I have added the sys.path entry as follows but it still does not recognize it. Please note that the error occurs on 2.7 but works absolutely fine on 3.4
user> cd ~/tests/
user> ls
__pycache__ backups inputs libraries openflow.py test_flow.py
user> ls libraries/
__pycache__ controller_utils.py general_utils.py general_utils.pyc tc_name_list.py test_case_utils.py
user> python
Python 2.7.4 (default, Jun 1 2015, 10:35:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
>>> import sys
>>> sys.path.append('libraries/')
>>> from libraries.controller_utils import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named libraries.controller_utils
Your libraries package is missing the __init__.py file. You can create an empty file with that name and then:
from libraries.controller_utils import *
should work.
Alternatively, if you don't want to turn libraries into a package you should add its path to sys.path and import controller_utils:
import sys
sys.path.append('libraries/')
from controller_utils import *
Note that the error is due to the fact that python2 requires the existence of __init__.py to import from packages while python3.3+ provides namespace packages (see PEP420). That's why the import doesn't fail in python3.4.
If you want your code to work in both python2 and python3 in the same way you should always add __init__.py file to packages and use from __future__ import absolute_import in your files.
See PEP 0404.
In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported. In addition, star imports (e.g. from x import *) are only permitted in module level code.
If libraries was in the same directory this would have happened to avoid clashes with packages installed at the system level. It would have been an implicit relative import.
You should be able to navigate to the correct location of the module using .., like:
from ..libraries.controller_utils import *
# or, depending of you directory structure
# put as many dots as directories you need to get out of
from ....common.libraries.controller_utils import *
But your case seems to be related to the star import. In Python 3 you can only use star imports (from x import *) at the top level of the file, i.e. not inside a function or class definition.
Running python on Snow Leopard, and I can't import the 'time' module. Works in ipython. Don't have any .pythonrc files being loaded. Scripts that 'import time' using the same interpreter run fine. Have no idea how to troubleshoot this. Anyone have an idea?
[wiggles#bananas ~]$ python2.6
Python 2.6.6 (r266:84292, Sep 1 2010, 14:27:13)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "time.py", line 4, in <module>
t = now.strftime("%d-%m-%Y-%H-%M")
AttributeError: struct_time
>>>
[wiggles#bananas ~]$ ipython-2.6
Python 2.6.6 (r266:84292, Sep 1 2010, 14:27:13)
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import time
In [2]:
Look for a file called time.py. It looks like Python is importing that, instead of the one from the standard library:
File "time.py", line 4, in <module>
The solution is to rename the file something other than "time.py".
By the way, you can find the path to the offending file by opening a Python REPL and typing.
In [1]: import time
In [2]: time.__file__
or
In [3]: time # This shows the path as part of the repr