Difference between revisions of "Python"
Jump to navigation
Jump to search
Line 35: | Line 35: | ||
The CompletedProcess returned has (args, returncode, stdout, stderr) | The CompletedProcess returned has (args, returncode, stdout, stderr) | ||
+ | |||
+ | ==Variables== | ||
+ | Variables are always pointers to objects. | ||
+ | <syntaxhighlight lang=python> | ||
+ | a = 2 | ||
+ | b = 2 | ||
+ | </syntaxhighlight> | ||
+ | Point to the same object (the immutable integer '2') | ||
+ | |||
+ | Variables are local by default. If a routine has any assignment to a variable it is local. If you have defined a variable outside a routine and need assignments to it in the routine you have to declare it global explicitly. | ||
+ | Variables are always pointers to objects. | ||
+ | <syntaxhighlight lang=python> | ||
+ | a = 'a string' | ||
+ | |||
+ | def main(): | ||
+ | global a | ||
+ | print(a) | ||
+ | a = "This would fail with 'local variable 'a' referenced before assignment' if 'a' was not declared as global" | ||
+ | |||
+ | main() | ||
+ | </syntaxhighlight> | ||
+ | [[https://www.geeksforgeeks.org/global-local-variables-python/ Geeks for Geeks]] has as good page about this. |
Revision as of 09:45, 9 October 2018
Generic things:
The Python style guide is described in [PEP 8]
Modules
To add the location of your own modules to the python search path put it in the PYTHONPATH variable.
- import sys
- Number of system variables
- sys.argv
- List of everything on the commandline. sys.argv[0] is the program itself.
- import getopt
- Module to parse the commandline arguments (sys.argv). Default available
- import subprocess
- Module to execute shell commands
In python2
import subprocess
exitcode = subprocess.call("<any command>")
commandoutput = subprocess.check_output("<any command>")
Use ("command",shell=True) to have the call work like it would on the commandline
In python3
import subprocess
CompletedProcess = subprocess.run("<any command>")
The CompletedProcess returned has (args, returncode, stdout, stderr)
Variables
Variables are always pointers to objects.
a = 2
b = 2
Point to the same object (the immutable integer '2')
Variables are local by default. If a routine has any assignment to a variable it is local. If you have defined a variable outside a routine and need assignments to it in the routine you have to declare it global explicitly. Variables are always pointers to objects.
a = 'a string'
def main():
global a
print(a)
a = "This would fail with 'local variable 'a' referenced before assignment' if 'a' was not declared as global"
main()
[Geeks for Geeks] has as good page about this.